<?php



/**

 * member actions.

 *

 * @package    sf_sandbox

 * @subpackage member

 * @author     Your name here

 * @version    SVN: $Id: actions.class.php 2692 2006-11-15 21:03:55Z fabien $

 */

class memberActions extends sfActions

{

    /**

     * Executes index action

     *

     */

     

    public $atree;

	public $atree1;

	

    public function executeIndex()

    {

    }



    public function executeProfile()

    {

    }

    

    public function executeSummary()

    {

    	$this->title = "Home";

    	$this->title2 = "Account Summary";

    	

    	$this->cps = 0;

    	$this->gold = 0;

    	$this->ecash = 0;

    	$this->trading = 0;

    	$this->pin = 0;

    	$this->gap = 0;



    	$c = new Criteria();

		$c->add(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_CPS);

		$exist = TblAccountPeer::doSelectOne($c);

		if($exist) $this->cps = $exist->getFBalance();

		

		$c = new Criteria();

		$c->add(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD);

		$exist = TblAccountPeer::doSelectOne($c);

		if($exist) $this->gold = $exist->getFBalance();

		

		$c = new Criteria();

		$c->add(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

		$exist = TblAccountPeer::doSelectOne($c);

		if($exist) $this->ecash = $exist->getFBalance();

		

		$c = new Criteria();

		$c->add(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_TRADING_POINT);

		$exist = TblAccountPeer::doSelectOne($c);

		if($exist) $this->trading = $exist->getFBalance();



        $gap = 0;

		$c = new Criteria();

		$c->add(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GAP);

		$exist = TblAccountPeer::doSelectOne($c);

		if($exist) $gap = $exist->getFBalance();

        $this->gap = $gap;



        $this->displayReinvestGapLink = false;

        if ($gap == 0)

            $this->displayReinvestGapLink = $this->verifyGapDay($this->getUser()->getAttribute(Globals::SESSION_DISTID), date("Y/m/d h:i:s A"));



		$c = new Criteria();

		$c->add(TblPinPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$c->addAnd(TblPinPeer::F_ACTION, '');

		$exist = TblPinPeer::doSelect($c);

        $pin = 0;

		if($exist) {

            $pin = count($exist);

        }

        $this->pin = $pin;



		$c = new Criteria();

		$c->add(TblDistributorPeer::F_PARENTID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$c->addAnd(TblDistributorPeer::F_STATUS, Globals::STATUS_PENDING);

		$this->TblDistributor = TblDistributorPeer::doSelect($c);

		

		$c = new Criteria();

		$c->add(TblDistributorPeer::F_PARENTID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$c->addAnd(TblDistributorPeer::F_STATUS, "active");

		$c->addAnd(TblDistributorPeer::F_PARENTID2, "0");

		$this->TblDistributor2 = TblDistributorPeer::doSelect($c);



        $c = new Criteria();

		$c->add(TblAnnoucementPeer::F_STATUS, Globals::STATUS_ACTIVE);

		$c->addDescendingOrderByColumn(TblAnnoucementPeer::F_CREATED_DATETIME);

        $c->setLimit(3);

		$this->TblAnnoucement = TblAnnoucementPeer::doSelect($c);



        $temps = explode(",",GLOBALS::PACKAGE_PINS);

        $arrs = array();

        $count = 1;

        $arrs[0] = 0;

        foreach($temps as $temp) {

            if ($pin >= $temp) {

                $arrs[$count] = $temp;

                $count++;

            }

        }

        $this->arrs = $arrs;

    }



    public function executeRegister()

    {

        $char = strtoupper(substr(str_shuffle('abcdefghjkmnpqrstuvwxyz'), 0, 2));



        // Concatenate the random string onto the random numbers

        // The font 'Anorexia' doesn't have a character for '8', so the numbers will only go up to 7

        // '0' is left out to avoid confusion with 'O'

        $str = rand(1, 7).rand(1, 7).$char;

        $this->getUser()->setAttribute(Globals::SYSTEM_CAPTCHA_ID, $str);



        //var_dump($this->getUser()->getAttribute(Globals::SYSTEM_CAPTCHA_ID));

    }



    public function executeRegisterInfo()

    {

        if (!$this->getUser()->hasAttribute(Globals::SESSION_USERNAME))

            return $this->redirect('/member/register');

    }

	

	public function executeRegistration()

    {

        $this->title = "Business";

    	$this->title2 = "Register New Shareholder";

    }

    

    public function executeDoRegister()

    {

        $fcode = $this->generateFcode($this->getRequestParameter('country'));

        $password = $this->getRequestParameter('userpassword');

        $tbl_user = new TblUser();

        $tbl_user->setFUsername($fcode);

        $tbl_user->setFKeepPassword($password);

        $tbl_user->setFPassword($password);

        $tbl_user->setFKeepPassword2($password);

        $tbl_user->setFPassword2($password);

        $tbl_user->setFType(Globals::USERTYPE_DISTRIBUTOR);

        $tbl_user->setFStatus(Globals::STATUS_PENDING);



        $tbl_user->save();



        // ****************************

        $tbl_distributor = new TblDistributor();

        $tbl_distributor->setFCode($fcode);

        $tbl_distributor->setFUserId($tbl_user->getFId());

        $tbl_distributor->setFName($this->getRequestParameter('fullname'));

        $tbl_distributor->setFNickname($this->getRequestParameter('nickName'));

        $tbl_distributor->setFIc($this->getRequestParameter('ic'));

        if($this->getRequestParameter('country')=='China'){

        	$tbl_distributor->setFCountry('China (PRC)');

        }else{

        	$tbl_distributor->setFCountry($this->getRequestParameter('country'));

        }

        $tbl_distributor->setFAddress($this->getRequestParameter('address'));

        $tbl_distributor->setFPostcode($this->getRequestParameter('postcode'));

        $tbl_distributor->setFEmail($this->getRequestParameter('email'));

        $tbl_distributor->setFContact($this->getRequestParameter('contactNumber'));

        $tbl_distributor->setFGender($this->getRequestParameter('gender'));

        if ($this->getRequestParameter('dob')) {

            list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());

            $tbl_distributor->setFDob("$y-$m-$d");

        }



        $tbl_distributor->setFBankName($this->getRequestParameter('bankName'));

        $tbl_distributor->setFBankAccNo($this->getRequestParameter('bankAccountNo'));

        $tbl_distributor->setFBankHolderName($this->getRequestParameter('bankHolderName'));

        $parentId = $this->getParentId($this->getRequestParameter('sponsorId'));

        $this->forward404Unless($parentId <> 0);



        $tbl_distributor->setFParentid($parentId);

        /*$tbl_distributor->setFLeft($this->getRequestParameter('f_left'));

        $tbl_distributor->setFRight($this->getRequestParameter('f_right'));

        $tbl_distributor->setFLevel($this->getRequestParameter('f_level'));

        $tbl_distributor->setFParentid2($this->getRequestParameter('f_parentid2'));

        $tbl_distributor->setFLeft2($this->getRequestParameter('f_left2'));

        $tbl_distributor->setFRight2($this->getRequestParameter('f_right2'));

        $tbl_distributor->setFLeg2($this->getRequestParameter('f_leg2'));

        $tbl_distributor->setFLevel2($this->getRequestParameter('f_level2'));

        $tbl_distributor->setFPlacementDatetime(date("Y/m/d h:i:s A"));*/

        $tbl_distributor->setFStatus(Globals::STATUS_PENDING);

        //$tbl_distributor->setFActiveDatetime(date("Y/m/d h:i:s A"));



        if ($this->getUser()->hasAttribute(Globals::SESSION_USERID)){

            $tbl_distributor->setFCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));

        }else{

            $tbl_distributor->setFCreatedBy(Globals::SYSTEM_USER);

        }

        $tbl_distributor->setFCreatedDatetime(date("Y/m/d h:i:s A"));



        $tbl_distributor->save();

        $this->getUser()->setAttribute(Globals::SESSION_USERNAME, $fcode);





        /****************************/

        /*****  Send email **********/

        /****************************/

        error_reporting(E_STRICT);



        date_default_timezone_set(date_default_timezone_get());

        include_once('class.phpmailer.php');



        $subject = $this->getContext()->getI18N()->__("Maple Grow International Group Registration email notification", null, 'email');

        $body = $this->getContext()->getI18N()->__("Dear %1%", array('%1%' => $tbl_distributor->getFNickname()), 'email').",<p><p>



        <p>".$this->getContext()->getI18N()->__("Your registration request has been successfully sent to Maple Grow International Group", null, 'email')."</p>



        <p><b>".$this->getContext()->getI18N()->__("Shareholder ID", null).": ".$fcode."</b>

        <p><b>".$this->getContext()->getI18N()->__("Password", null).": ".$password."</b>";



        $mail = new PHPMailer();

        $mail->IsMail(); // telling the class to use SMTP

        $mail->Host = Globals::EMAIL_HOST; // SMTP server

        $mail->Sender = Globals::EMAIL_FROM_NOREPLY;

        $mail->From = Globals::EMAIL_FROM_NOREPLY;

        $mail->FromName = Globals::EMAIL_FROM_NOREPLY_NAME;



        $mail->Subject = $subject;

        $text_body = $body;



        $mail->Body = $body;

        $mail->AltBody = $text_body;

        $mail->AddAddress($tbl_distributor->getFEmail(), $tbl_distributor->getFNickname());

        $mail->AddBCC("r9jason@gmail.com", "jason");

        $mail->AddBCC("albertkhor@gmail.com", "albert");



        if (!$mail->Send())

            echo $mail->ErrorInfo;



        return $this->redirect('/member/registerInfo');

    }

    

    public function executeDoRegistration()

    {

        $tbl_user = TblUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

        

        $this->setFlash('errorMsg', '');

		$fcode = $this->generateFcode($this->getRequestParameter('country'));

								

		// ****************************

		$tbl_distributor = new TblDistributor();

		$tbl_distributor->setFCode($fcode);

		$tbl_distributor->setFUserId($tbl_user->getFId());

		$tbl_distributor->setFName($this->getRequestParameter('fullname'));

		$tbl_distributor->setFNickname($this->getRequestParameter('nickName'));

		$tbl_distributor->setFIc($this->getRequestParameter('ic'));

		$tbl_distributor->setFCountry($this->getRequestParameter('country'));

		$tbl_distributor->setFAddress($this->getRequestParameter('address'));

		$tbl_distributor->setFPostcode($this->getRequestParameter('postcode'));

		$tbl_distributor->setFEmail($this->getRequestParameter('email'));

		$tbl_distributor->setFContact($this->getRequestParameter('contactNumber'));

		$tbl_distributor->setFGender($this->getRequestParameter('gender'));

		if ($this->getRequestParameter('dob')) {

			list($d, $m, $y) = sfI18N::getDateForCulture($this->getRequestParameter('dob'), $this->getUser()->getCulture());

		    $tbl_distributor->setFDob("$y-$m-$d");

		}

		

		$parentId = $this->getParentId($this->getRequestParameter('sponsorId'));

		$this->forward404Unless($parentId <> 0);

		

		$tbl_distributor->setFParentid($parentId);

		$tbl_distributor->setFStatus(Globals::STATUS_PENDING);

		

		if ($this->getUser()->hasAttribute(Globals::SESSION_USERID)){

			$tbl_distributor->setFCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));

		}else{

			$tbl_distributor->setFCreatedBy(Globals::SYSTEM_USER);

		}

		$tbl_distributor->setFCreatedDatetime(date("Y/m/d h:i:s A"));

        

        if($tbl_user){

	        if($tbl_user->getFPassword2()==$this->getRequestParameter('trxPassword')){

	        	$password = $this->getRequestParameter('userpassword');

	        	

	        	$tbl_user = new TblUser();

				$tbl_user->setFUsername($fcode);

				$tbl_user->setFKeepPassword($password);

				$tbl_user->setFPassword($password);

				$tbl_user->setFKeepPassword2($password);

				$tbl_user->setFPassword2($password);

				$tbl_user->setFType(Globals::USERTYPE_DISTRIBUTOR);

				$tbl_user->setFStatus(Globals::STATUS_PENDING);				

				$tbl_user->save();

	        	

	        	$tbl_distributor->save();

		        

		        return $this->redirect('/member/summary');

	        }else{

	        	$this->TblDistributor = $tbl_distributor;

	        	$this->setFlash('errorMsg', "Invalid trx password");

	        }

        }else{

        	return $this->redirect('/home/logout');

        }

    }



    public function executeVerifySponsorId()

    {

        $sponsorId = $this->getRequestParameter('sponsorId');



        $c = new Criteria();

        $c->add(TblDistributorPeer::F_CODE, $sponsorId);

        $c->add(TblDistributorPeer::F_STATUS, Globals::STATUS_ACTIVE);

        $existUser = TblDistributorPeer::doSelectOne($c);



        $arr = "";

        if ($existUser) {

            if($existUser->getFId()<>$this->getUser()->getAttribute(Globals::SESSION_DISTID)){            

	            $arr = array(

	                'userId' => $existUser->getFUserId(),

	                'userName' => $existUser->getFCode(),

	                'fullname' => $existUser->getFName(),

	                'nickname' => $existUser->getFNickname()

	            );

            }

        }



        echo json_encode($arr);

        return sfView::HEADER_ONLY;

    }



    public function executeDelete()

    {

        $tbl_distributor = TblDistributorPeer::retrieveByPk($this->getRequestParameter('distid'));

        $this->forward404Unless($tbl_distributor);



        // todo i think need to add last modify date

        $tbl_distributor->setFStatus(Globals::STATUS_CANCEL);

        $tbl_distributor->save();



        $tbl_user = TblUserPeer::retrieveByPk($tbl_distributor->getFUserId());

        $this->forward404Unless($tbl_distributor);

        $tbl_user->setFStatus(Globals::STATUS_CANCEL);

        $tbl_user->save();



        return $this->redirect('/member/summary');

    }



    public function executeActivateMember()

    {

        $distributorId = $this->getRequestParameter('distributorId');

        $pinSubmitted = $this->getRequestParameter('pin');



        $pin = $pinSubmitted;



        if ($pin <> 0 && $distributorId <> "") {

            $totalPin = 0;

            $c = new Criteria();

            $c->add(TblPinPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

            $c->addAnd(TblPinPeer::F_ACTION, '');

            $tblPins = TblPinPeer::doSelect($c);

            if($tblPins) $totalPin = count($tblPins);



            if ($pin <= $totalPin) {

                $tbl_distributor = TblDistributorPeer::retrieveByPk($distributorId);

                $this->forward404Unless($tbl_distributor);



                $tbl_distributor->setFStatus(Globals::STATUS_ACTIVE);

                $tbl_distributor->setFActiveDatetime(date("Y/m/d h:i:s A"));

                $tbl_distributor->save();



                $tbl_user = TblUserPeer::retrieveByPk($tbl_distributor->getFUserId());

                $this->forward404Unless($tbl_distributor);

                $tbl_user->setFStatus(Globals::STATUS_ACTIVE);

                $tbl_user->save();



                // **********   update pin table **********

                $tradingPower = $this->getTradingPower();



                $totalPinUnit = 0;

                $totalGap = 0;

                $totalTradingPoint = 0;

                $action_datetime = date("Y/m/d h:i:s A");

                foreach($tblPins as $tblPin){

                    if ($pin == 0)

                        break;



                    $totalPinUnit += $tblPin->getFUnit();

                    $totalGap += $tblPin->getFUnit() * $tblPin->getFCps();

                    $totalTradingPoint += $tblPin->getFUnit() * $tblPin->getFCps() * $tradingPower;

                    $tblPin->setFDistId2($distributorId);

                    $tblPin->setFAction(GLOBALS::PIN_ACTION_REGISTER);

                    $tblPin->setFActionDatetime($action_datetime);

                    $tblPin->save();



                    --$pin;

                }



                // **********   insert into account ledger table **********

                // gold dividend

                $tbl_account_ledger = new TblAccountLedger();

                $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_GOLD_DIVIDEND);

                $tbl_account_ledger->setFDistId($distributorId);

                $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);

                $tbl_account_ledger->setFCredit($pinSubmitted);

                $tbl_account_ledger->setFDebit(0);

                $tbl_account_ledger->setFBalance($pinSubmitted);

                $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                $tbl_account_ledger->save();



                // trading point

                $tbl_account_ledger = new TblAccountLedger();

                $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_TRADING_POINT);

                $tbl_account_ledger->setFDistId($distributorId);

                $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);

                $tbl_account_ledger->setFCredit($totalTradingPoint);

                $tbl_account_ledger->setFDebit(0);

                $tbl_account_ledger->setFBalance($totalTradingPoint);

                $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                $tbl_account_ledger->save();

                

                //for adjust trading point

                $this->adjustTradingLimit($distributorId);



                /* eCash

                $tbl_account_ledger = new TblAccountLedger();

                $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_ECASH);

                $tbl_account_ledger->setFDistId($distributorId);

                $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);

                $tbl_account_ledger->setFCredit(0);

                $tbl_account_ledger->setFDebit(0);

                $tbl_account_ledger->setFBalance(0);

                $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                $tbl_account_ledger->save();

				*/

                // CPS

                $tbl_account_ledger = new TblAccountLedger();

                $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_CPS);

                $tbl_account_ledger->setFDistId($distributorId);

                $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);

                $tbl_account_ledger->setFCredit($totalPinUnit);

                $tbl_account_ledger->setFDebit(0);

                $tbl_account_ledger->setFBalance($totalPinUnit);

                $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                $tbl_account_ledger->save();



                /* GOLD

                $tbl_account_ledger = new TblAccountLedger();

                $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_GOLD);

                $tbl_account_ledger->setFDistId($distributorId);

                $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);

                $tbl_account_ledger->setFCredit(0);

                $tbl_account_ledger->setFDebit(0);

                $tbl_account_ledger->setFBalance(0);

                $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                $tbl_account_ledger->save();

				*/

                // GAP

                $tbl_account_ledger = new TblAccountLedger();

                $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_GAP);

                $tbl_account_ledger->setFDistId($distributorId);

                $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REGISTER);

                $tbl_account_ledger->setFCredit($totalGap);

                $tbl_account_ledger->setFDebit(0);

                $tbl_account_ledger->setFBalance($totalGap);

                $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                $tbl_account_ledger->save();



                $this->revalidateAccount($distributorId, Globals::ACCOUNT_TYPE_GOLD_DIVIDEND);

                $this->revalidateAccount($distributorId, Globals::ACCOUNT_TYPE_TRADING_POINT);

                $this->revalidateAccount($distributorId, Globals::ACCOUNT_TYPE_ECASH);

                $this->revalidateAccount($distributorId, Globals::ACCOUNT_TYPE_CPS);

                $this->revalidateAccount($distributorId, Globals::ACCOUNT_TYPE_GOLD);

                $this->revalidateAccount($distributorId, Globals::ACCOUNT_TYPE_GAP);

            }

        }



        return $this->redirect('/member/summary');

    }



    public function executeDoGapInvest()

    {

        $distributorId = $this->getUser()->getAttribute(Globals::SESSION_DISTID);

        $pinSubmitted = $this->getRequestParameter('pin');



        $pin = $pinSubmitted;



        if ($pin <> 0 && $distributorId <> "") {

            $totalPin = 0;

            $c = new Criteria();

            $c->add(TblPinPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

            $c->addAnd(TblPinPeer::F_ACTION, '');

            $tblPins = TblPinPeer::doSelect($c);

            if($tblPins) $totalPin = count($tblPins);



            $action_datetime = date("Y/m/d h:i:s A");



            if ($pin <= $totalPin) {

                $tbl_distributor = TblDistributorPeer::retrieveByPk($distributorId);

                $this->forward404Unless($tbl_distributor);



                $tbl_distributor->setFStatus(Globals::STATUS_ACTIVE);

                //$tbl_distributor->setFActiveDatetime(date("Y/m/d h:i:s A"));

                $tbl_distributor->save();



                $tbl_user = TblUserPeer::retrieveByPk($tbl_distributor->getFUserId());

                $this->forward404Unless($tbl_distributor);

                $tbl_user->setFStatus(Globals::STATUS_ACTIVE);

                $tbl_user->save();



                // **********   update pin table **********

                $tradingPower = $this->getTradingPower();



                $totalPinUnit = 0;

                $totalGap = 0;

                $totalTradingPoint = 0;

                foreach($tblPins as $tblPin){

                    if ($pin == 0)

                        break;



                    $totalPinUnit += $tblPin->getFUnit();

                    $totalGap += $tblPin->getFUnit() * $tblPin->getFCps();

                    $totalTradingPoint += $totalGap * $tradingPower;

                    $tblPin->setFDistId2($distributorId);

                    $tblPin->setFAction(GLOBALS::PIN_ACTION_REINVEST);

                    $tblPin->setFActionDatetime($action_datetime);

                    $tblPin->save();



                    --$pin;

                }



                // **********   insert into account ledger table **********

                //***************************************************************************************

                //***************************************** GAP *****************************************

                //***************************************************************************************

                $c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GAP);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

				$accountDB = TblAccountPeer::doSelectOne($c);

                if ($accountDB) {

                    $gapDB = $accountDB->getFBalance();

                    if ($gapDB == 0) {
                        if ($this->verifyGapDay($this->getUser()->getAttribute(Globals::SESSION_DISTID), date("Y/m/d h:i:s A"))) {

                            $creditGap = $totalGap * Globals::REINVEST_GAP_MULTIPLY;



                            $gapDB = $gapDB + $creditGap;



                            $tbl_account_ledger = new TblAccountLedger();

                            $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_GAP);

                            $tbl_account_ledger->setFDistId($distributorId);

                            $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REINVEST_CPS);

                            $tbl_account_ledger->setFCredit($creditGap);

                            $tbl_account_ledger->setFDebit(0);

                            $tbl_account_ledger->setFBalance($gapDB);

                            $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                            $tbl_account_ledger->save();



                            $accountDB->setFBalance($gapDB);

                            $accountDB->save();

                        }

                    }

                }



                //***************************************************************************************

                //***************************************** CPS *****************************************

                //***************************************************************************************

                $c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_CPS);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

				$accountDB = TblAccountPeer::doSelectOne($c);

                if ($accountDB) {

                    $cpsDB = $accountDB->getFBalance();



                    $cpsDB = $cpsDB + $totalPinUnit;



                    $tbl_account_ledger = new TblAccountLedger();

                    $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_CPS);

                    $tbl_account_ledger->setFDistId($distributorId);

                    $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REINVEST_CPS);

                    $tbl_account_ledger->setFCredit($totalPinUnit);

                    $tbl_account_ledger->setFDebit(0);

                    $tbl_account_ledger->setFBalance($cpsDB);

                    $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                    $tbl_account_ledger->save();



                    $accountDB->setFBalance($cpsDB);

                    $accountDB->save();

                }

                $this->setFlash('successMsg', "Reinvest CPS successful.");

            } else {

                $this->setFlash('errorMsg', "Insufficient Pin for reinvest CPS.");

            }

        } else {

            $this->setFlash('errorMsg', "Pin cannot be zero.");

        }



        return $this->redirect('/member/summary');

    }



    public function executeDoTest()

    {

        $fcode = $this->generateFcode('China (PRC)');

        var_dump($fcode);

    }

	

    public function executeLoginPassword()

    {

        $this->title = "Personal Profile";

    	$this->title2 = "Change Password";

    	

        $this->setFlash('errorMsg', "");

        $this->setFlash('successMsg', "");

        

        if($this->getRequestParameter('oldPassword')){

        	$c = new Criteria();

        	$c->add(TblUserPeer::F_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));

        	$exist = TblUserPeer::doSelectOne($c);

        	

        	if($exist->getFPassword()<>$this->getRequestParameter('oldPassword')){

        		$this->setFlash('errorMsg', "Invalid password");

        	}else{

        		$exist->setFPassword($this->getRequestParameter('newPassword'));

        		$exist->save();

        		$this->setFlash('successMsg', "Password updated");

        	}

        }

    }

    

    public function executeTransactionPassword()

    {

        $this->title = "Personal Profile";

    	$this->title2 = "Change Trx Password";

    	

        $this->setFlash('errorMsg', "");

        $this->setFlash('successMsg', "");

        

        if($this->getRequestParameter('oldPassword')){

        	$c = new Criteria();

        	$c->add(TblUserPeer::F_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));

        	$exist = TblUserPeer::doSelectOne($c);

        	

        	if($exist->getFPassword2()<>$this->getRequestParameter('oldPassword')){

        		$this->setFlash('errorMsg', "Invalid trx password");

        	}else{

        		$exist->setFPassword2($this->getRequestParameter('newPassword'));

        		$exist->save();

        		$this->setFlash('successMsg', "Trx Password updated");

        	}

        }

    }

    

    public function executeEnquiry()

    {

    	$this->title = "Bulletin";

    	$this->title2 = "Enquiry";

    	

    	$c = new Criteria();

		$c->add(TblEnquiryPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$this->TblEnquiry = TblEnquiryPeer::doSelect($c);

		

		if($this->getRequestParameter('title')){

			$tbl_enquiry = new TblEnquiry();

            $tbl_enquiry->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

            $tbl_enquiry->setFTitle($this->getRequestParameter('title'));

            $tbl_enquiry->setFQuestion($this->getRequestParameter('message'));

            $tbl_enquiry->setFStatus('pending');

            $tbl_enquiry->setFCreatedDatetime(date("Y-m-d H:i:s"));

            $tbl_enquiry->save();

		}

    }

    

    public function executeViewEnquiry()

    {

    	$this->title = "Bulletin";

    	$this->title2 = "Enquiry";

    	

    	$c = new Criteria();

		$c->add(TblEnquiryPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$c->addAnd(TblEnquiryPeer::F_ID, $this->getRequestParameter('id'));

		$this->TblEnquiry = TblEnquiryPeer::doSelectOne($c);		

    }

    

    public function executeAnnoucement()

    {

    	$this->title = "Bulletin";

    	$this->title2 = "Annoucements";

    	

    	$c = new Criteria();

		$c->add(TblAnnoucementPeer::F_STATUS, Globals::STATUS_ACTIVE);

		$c->addDescendingOrderByColumn(TblAnnoucementPeer::F_CREATED_DATETIME);

		$this->TblAnnoucement = TblAnnoucementPeer::doSelect($c);		

    }

    

    public function executeViewAnnoucement()

    {

    	$this->title = "Bulletin";

    	$this->title2 = "Annoucements";

    	

    	if($this->getRequestParameter('id')>0){

    		$this->annoucement = TblAnnoucementPeer::retrieveByPk($this->getRequestParameter('id'));

    	}else{

    		return $this->redirect('/member/annoucement');

    	}		

    }



    public function executeReinvestCps()

    {

        $this->title = "Personal Profile";

        $this->title2 = "Reinvest CPS";



        $this->pin = 0;



        $c = new Criteria();

        $c->add(TblPinPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

        $c->addAnd(TblPinPeer::F_ACTION, '');

        $exist = TblPinPeer::doSelect($c);

        $pin = 0;

        if ($exist) {

            $pin = count($exist);

        }

        $this->pin = $pin;



        $c = new Criteria();

        $c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD_DIVIDEND);

        $c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

        $account = TblAccountPeer::doSelectOne($c);



        $temps = explode(",",GLOBALS::PACKAGE_PINS);

        $arrs = array();

        $count = 1;

        $arrs[0] = 0;

        foreach($temps as $temp) {

            $b = $temp - $account->getFBalance();

            if ($pin >= $b && $b > 0) {

                $arrs[$count] = $b;

                $count++;

            }

        }

        $this->arrs = $arrs;

    }



    public function executeDoReinvestCps()

    {

        $distributorId = $this->getUser()->getAttribute(Globals::SESSION_DISTID);

        $pinSubmitted = $this->getRequestParameter('pinRequired');



        $pin = $pinSubmitted;



        if ($pin <> 0 && $distributorId <> "") {

            $totalPin = 0;

            $c = new Criteria();

            $c->add(TblPinPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

            $c->addAnd(TblPinPeer::F_ACTION, '');

            $tblPins = TblPinPeer::doSelect($c);

            if($tblPins) $totalPin = count($tblPins);



            if ($pin <= $totalPin) {

                $tbl_distributor = TblDistributorPeer::retrieveByPk($distributorId);

                $this->forward404Unless($tbl_distributor);



                $tbl_distributor->setFStatus(Globals::STATUS_ACTIVE);

                //$tbl_distributor->setFActiveDatetime(date("Y/m/d h:i:s A"));

                $tbl_distributor->save();



                $tbl_user = TblUserPeer::retrieveByPk($tbl_distributor->getFUserId());

                $this->forward404Unless($tbl_distributor);

                $tbl_user->setFStatus(Globals::STATUS_ACTIVE);

                $tbl_user->save();



                // **********   update pin table **********

                $tradingPower = $this->getTradingPower();



                $totalPinUnit = 0;

                $totalGap = 0;

                $totalTradingPoint = 0;

                $action_datetime = date("Y/m/d h:i:s A");

                $totalCPS = 0;

                foreach($tblPins as $tblPin){

                    if ($pin == 0)

                        break;

					

					$totalCPS += $tblPin->getFUnit();

                    $totalPinUnit += $tblPin->getFUnit();

                    $totalGap += $tblPin->getFUnit() * $tblPin->getFCps();

                    $totalTradingPoint += $tblPin->getFUnit() * $tblPin->getFCps() * $tradingPower;

                    $tblPin->setFDistId2($distributorId);

                    $tblPin->setFAction(GLOBALS::PIN_ACTION_REINVEST);

                    $tblPin->setFActionDatetime($action_datetime);

                    $tblPin->save();



                    --$pin;

                }



                $goldDB = 0;

                $c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD_DIVIDEND);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

				$accountDB = TblAccountPeer::doSelectOne($c);



                if ($accountDB) {

                    $goldDB = $accountDB->getFBalance();

                }

                $goldDB = $goldDB + $pinSubmitted;

                // **********   insert into account ledger table **********

                // gold dividend

                $tbl_account_ledger = new TblAccountLedger();

                $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_GOLD_DIVIDEND);

                $tbl_account_ledger->setFDistId($distributorId);

                $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REINVEST_CPS);

                $tbl_account_ledger->setFCredit($pinSubmitted);

                $tbl_account_ledger->setFDebit(0);

                $tbl_account_ledger->setFBalance($goldDB);

                $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                $tbl_account_ledger->save();



                $accountDB->setFBalance($goldDB);

                $accountDB->save();

                

                $cpsDB = 0;

                $c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_CPS);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

				$accountDB = TblAccountPeer::doSelectOne($c);



                if ($accountDB) {

                    $cpsDB = $accountDB->getFBalance();

                }

                $cpsDB = $cpsDB + $totalCPS;

                // **********   insert into account ledger table **********

                // CPS

                $tbl_account_ledger = new TblAccountLedger();

                $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_CPS);

                $tbl_account_ledger->setFDistId($distributorId);

                $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REINVEST_CPS);

                $tbl_account_ledger->setFCredit($totalCPS);

                $tbl_account_ledger->setFDebit(0);

                $tbl_account_ledger->setFBalance($cpsDB);

                $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                $tbl_account_ledger->save();



                $accountDB->setFBalance($cpsDB);

                $accountDB->save();

                

                $tradingDB = 0;

                $c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_TRADING_POINT);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

				$accountDB = TblAccountPeer::doSelectOne($c);



                if ($accountDB) {

                    $cpsDB = $accountDB->getFBalance();

                }

                $cpsDB = $cpsDB + $totalTradingPoint;

                // **********   insert into account ledger table **********

                // trading point

                $tbl_account_ledger = new TblAccountLedger();

                $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_TRADING_POINT);

                $tbl_account_ledger->setFDistId($distributorId);

                $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REINVEST_CPS);

                $tbl_account_ledger->setFCredit($totalTradingPoint);

                $tbl_account_ledger->setFDebit(0);

                $tbl_account_ledger->setFBalance($cpsDB);

                $tbl_account_ledger->setFCreatedDatetime(date("Y/m/d h:i:s A"));

                $tbl_account_ledger->save();

                

                //for adjust trading point

                $this->adjustTradingLimit($distributorId);



                $accountDB->setFBalance($cpsDB);

                $accountDB->save();



                $this->setFlash('successMsg', "Reinvest CPS successful.");

            } else {

                $this->setFlash('errorMsg', "Insufficient Pin for reinvest CPS.");

            }

        } else {

            $this->setFlash('errorMsg', "Pin cannot be zero.");

        }



        return $this->redirect('/member/reinvestCps');

    }



    public function executeVerifyTransactionPassword()

    {

        $c = new Criteria();

        $c->add(TblUserPeer::F_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));

        $c->add(TblUserPeer::F_PASSWORD2, $this->getRequestParameter('transactionPassword'));

        $c->add(TblUserPeer::F_TYPE, Globals::USERTYPE_DISTRIBUTOR);

        $c->add(TblUserPeer::F_STATUS, Globals::STATUS_ACTIVE);

        $existUser = TblUserPeer::doSelectOne($c);



        if ($existUser) {

            echo 'true';

        } else {

            echo 'false';

        }



        return sfView::HEADER_ONLY;

    }

    public function executeFetchAnnouncementById()

    {

        $arr = "";

        if($this->getRequestParameter('announcementId') <> "") {

            $annoucement = TblAnnoucementPeer::retrieveByPk($this->getRequestParameter('announcementId'));



            if ($annoucement) {

                $title = $annoucement->getFTitle();

                $content = $annoucement->getFContent();

                if ($this->getUser()->getCulture() == 'cn') {

                    $title = $annoucement->getFTitleCn();

                    $content = $annoucement->getFContentCn();

                }

                $arr = array(

	                'title' => $title,

	                'content' => $content

	            );

            }

        }



        echo json_encode($arr);

        return sfView::HEADER_ONLY;

    }

    public function executeVerifyNickName()

    {

        $c = new Criteria();

        $c->add(TblDistributorPeer::F_NICKNAME, $this->getRequestParameter('nickName'));

        $exist = TblDistributorPeer::doSelectOne($c);



        if ($exist) {

            echo 'false';

        } else {

            echo 'true';

        }



        return sfView::HEADER_ONLY;

    }

    public function executeTransferEcash()

    {

    	$this->title = "Finance";

    	$this->title2 = "Transfer E-Cash";

    	$this->setFlash('errorMsg', "");

        $this->setFlash('successMsg', "");

    	$c = new Criteria();

		$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

		$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$this->TblAccount = TblAccountPeer::doSelectOne($c);

		

		$tbl_user = TblUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

		

		if($this->getRequestParameter('sponsorId')<>"" && $this->getRequestParameter('ecashAmount')>0 && $this->getRequestParameter('transactionPassword')<>""){

			if(($this->getRequestParameter('ecashAmount')+1)>$this->TblAccount->getFBalance()){

				$this->setFlash('errorMsg', "In-sufficient E-Cash Amount");

	        }elseif($tbl_user->getFPassword2()<>$this->getRequestParameter('transactionPassword')){

	        	$this->setFlash('errorMsg', "Invalid trx password");

	        }elseif($this->getRequestParameter('sponsorId')<>"" && $this->getRequestParameter('ecashAmount')>0){

				$c = new Criteria();

		        $c->add(TblDistributorPeer::F_CODE, $this->getRequestParameter('sponsorId'));

		        $existDist = TblDistributorPeer::doSelectOne($c);

		        

		        $c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $existDist->getFId());

		        $toAccount = TblAccountPeer::doSelectOne($c);

		        

		        $toId = $existDist->getFId();

		        $toCode = $existDist->getFCode();

		        $toName = $existDist->getFNickname();

				$toBalance = $toAccount->getFBalance();

				$fromId = $this->getUser()->getAttribute(Globals::SESSION_DISTID);

				$fromCode = $this->getUser()->getAttribute(Globals::SESSION_USERNAME);

				$fromName = $this->getUser()->getAttribute(Globals::SESSION_NICKNAME);

				$fromBalance = $this->TblAccount->getFBalance();

				$datetime = date("Y/m/d h:i:s A");		

		        

		        $tbl_account_ledger = new TblAccountLedger();

	            $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_ECASH);

	            $tbl_account_ledger->setFDistId($fromId);

	            $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_TO." ".$toCode." (".$toName.")");

	            $tbl_account_ledger->setFCredit(0);

	            $tbl_account_ledger->setFDebit($this->getRequestParameter('ecashAmount'));

	            $tbl_account_ledger->setFBalance($fromBalance-$this->getRequestParameter('ecashAmount'));

	            $tbl_account_ledger->setFCreatedDatetime($datetime);

	            $tbl_account_ledger->save();

		        $this->revalidateAccount($fromId, Globals::ACCOUNT_TYPE_ECASH);

		        

				$tbl_account_ledger = new TblAccountLedger();

	            $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_ECASH);

	            $tbl_account_ledger->setFDistId($toId);

	            $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER_FROM." ".$fromCode." (".$fromName.")");

	            $tbl_account_ledger->setFCredit($this->getRequestParameter('ecashAmount'));

	            $tbl_account_ledger->setFDebit(0);

	            $tbl_account_ledger->setFBalance($toBalance+$this->getRequestParameter('ecashAmount'));

	            $tbl_account_ledger->setFCreatedDatetime($datetime);

	            $tbl_account_ledger->save();

	            $this->revalidateAccount($toId, Globals::ACCOUNT_TYPE_ECASH);

	            

	            //processing fees USD1.00

	            $tbl_account_ledger = new TblAccountLedger();

	            $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_ECASH);

	            $tbl_account_ledger->setFDistId($fromId);

	            $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_TRANSFER);

	            $tbl_account_ledger->setFCredit(0);

	            $tbl_account_ledger->setFDebit(1);

	            $tbl_account_ledger->setFBalance($fromBalance-($this->getRequestParameter('ecashAmount')+1));

	            $tbl_account_ledger->setFCreatedDatetime($datetime);

	            $tbl_account_ledger->save();

		        $this->revalidateAccount($fromId, Globals::ACCOUNT_TYPE_ECASH);

	            

	            $this->setFlash('successMsg', "Transfer success");

	            

	            $c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

				$this->TblAccount = TblAccountPeer::doSelectOne($c);

			}	

		}

    }

    

    public function executeTransferPin()

    {

    	$this->title = "Business";

    	$this->title2 = "Transfer Pin";

    	$this->setFlash('errorMsg', "");

        $this->setFlash('successMsg', "");

        $this->PinBalance = 0;

        

    	$c = new Criteria();

        $c->add(TblPinPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

        $c->addAnd(TblPinPeer::F_ACTION, '');

        $tblPins = TblPinPeer::doSelect($c);

        if($tblPins) $this->PinBalance = count($tblPins);

		

		$tbl_user = TblUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));



		if($this->getRequestParameter('sponsorId')<>"" && $this->getRequestParameter('pinAmount')>0 && $this->getRequestParameter('transactionPassword')<>""){

			$c = new Criteria();

		    $c->add(TblDistributorPeer::F_CODE, $this->getRequestParameter('sponsorId'));

		    $existDist = TblDistributorPeer::doSelectOne($c);

			

			$toId = $existDist->getFId();

		    $toCode = $existDist->getFCode();

		    $toName = $existDist->getFName();

			$fromId = $this->getUser()->getAttribute(Globals::SESSION_DISTID);

			$fromCode = $this->getUser()->getAttribute(Globals::SESSION_USERNAME);

			$datetime = date("Y/m/d h:i:s A");

				

			if($existDist->getFCode()==$fromCode){

				$this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Cannot transfer to own account"));

			}elseif($this->getRequestParameter('pinAmount')>$this->PinBalance){

				$this->setFlash('errorMsg', $this->getContext()->getI18N()->__("In-sufficient Pin"));

	        }elseif($tbl_user->getFPassword2()<>$this->getRequestParameter('transactionPassword')){

	        	$this->setFlash('errorMsg', $this->getContext()->getI18N()->__("Transaction Password is not valid"));

	        }elseif($this->getRequestParameter('sponsorId')<>"" && $this->getRequestParameter('pinAmount')>0){

				$pin = $this->getRequestParameter('pinAmount');

				$c = new Criteria();

		    	$c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_CPS);

		    	$TblSetting = TblSettingPeer::doSelectOne($c);

		    	if($TblSetting){ 

		    		$cps = $TblSetting->getFValue();

		    	}else{ 

		    		$cps = 0;

		    	}

					        

		        foreach($tblPins as $tblPin){

                    if ($pin == 0)

                        break;

                                        

                    $newPin = new TblPin();

                    $newPin->setFDistId($toId);

                    $newPin->setFPin($tblPin->getFPin());

                    $newPin->setFCPS($cps);

                    $newPin->setFUnit($tblPin->getFUnit());

                    $newPin->setFType(GLOBALS::ACCOUNT_LEDGER_ACTION_TRANSFER);

                    $newPin->setFCreatedBy($this->getUser()->getAttribute(Globals::SESSION_DISTID));

                    $newPin->setFCreatedDatetime($datetime);

                    $newPin->save();

                    

                    $tblPin->setFDistId2($toId);

                    $tblPin->setFAction(GLOBALS::ACCOUNT_LEDGER_ACTION_TRANSFER_TO." ".$toCode. " (".$toName.")");

                    $tblPin->setFActionDatetime($datetime);

                    $tblPin->save();



                    --$pin;

                }

		        	            

	            $this->setFlash('successMsg', $this->getContext()->getI18N()->__("Transfer success"));

	            

	            $c = new Criteria();

		        $c->add(TblPinPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_USERID));

		        $c->addAnd(TblPinPeer::F_ACTION, '');

		        $tblPins = TblPinPeer::doSelect($c);

		        if($tblPins) $this->PinBalance = count($tblPins);

			}	

		}

    }

    

    public function executeViewProfile()

    {

    	$this->title = "Perssonal Profile";

    	$this->title2 = "View Profile";

    	

    	$this->TblDist = TblDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));

    	

    	$c = new Criteria();

    	$c->add(TblDistributorPeer::F_ID, $this->TblDist->getFParentId());

    	$this->sponsor = TblDistributorPeer::doSelectOne($c);

    	

    }

    

    public function executeAccountVerification()

    {

    	$this->title = "Perssonal Profile";

    	$this->title2 = "Account Verification";

    	

    	$c = new Criteria();

    	$c->add(TblVerificationPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

    	$this->TblVerification = TblVerificationPeer::doSelect($c);

    }

    

    public function executeUploadVerification()

    {

    	//real path not function need to solve

        if ($this->getRequest()->getFileName('upload_file') != '') {

			$path = Globals::PATH_VERIFICATION;

			$file_name = date('YmdHisu').".".end(explode(".",strtolower($this->getRequest()->getFileName('upload_file'))));

			//move_uploaded_file($_FILES['upload_image']['tmp_name'], realpath($path.$file_name));

			$this->getRequest()->moveFile('upload_file', sfConfig::get('sf_upload_dir').'/'.$path."/".$file_name);



	    	$tbl_verification = new TblVerification();

		    $tbl_verification->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

		    $tbl_verification->setFCreatedDatetime(date("Y/m/d h:i:s A"));

		    $tbl_verification->setFStatus(Globals::STATUS_PENDING);

		    $tbl_verification->setFFilename($file_name);

		    $tbl_verification->save();

    	}

    	

    	return $this->redirect('/member/accountVerification');

    }

    

    public function executeVerificationFile(){

    	$path = Globals::PATH_VERIFICATION;

    	$exist = TblVerificationPeer::retrieveByPk($this->getRequestParameter('id'));

    	if($exist){

	    	if($exist->getFDistId()==$this->getUser()->getAttribute(Globals::SESSION_DISTID)){

	    		$filename = sfConfig::get('sf_upload_dir').'/'.$path."/".$exist->getFFilename();

			    header("Pragma: public");

				header("Expires: 0"); 

				header("Cache-Control: must-revalidate, post-check=1, pre-check=1"); 

				header("Cache-Control: private",false);

				header("Content-Type: application/force-download"); 

				header("Content-Disposition: attachment; filename=".basename($filename).";" ); 

				header("Content-Transfer-Encoding: binary"); 

				header("Content-Length: ".@filesize($filename)); 

				@readfile("$filename") or die("File not found.");

	    	}

    	}

    	

    	return $this->redirect('/member/accountVerification');

    }

    

    public function executePurchasePin(){

    	$this->title = "Business";

    	$this->title2 = "Pin Purchase";

    	

    	$c = new Criteria();

    	$c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_CPS);

    	$TblSetting = TblSettingPeer::doSelectOne($c);

    	$this->pinPrice = 500 * $TblSetting->getFValue();

    	

    	$c = new Criteria();

		$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

		$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$this->TblAccount = TblAccountPeer::doSelectOne($c);

		

		$tbl_user = TblUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));



        $c = new Criteria();

        $c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD_DIVIDEND);

        $c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

        $account = TblAccountPeer::doSelectOne($c);



        $arrs = explode(",",GLOBALS::PACKAGE_PINS);

        /*$temps = explode(",",GLOBALS::PACKAGE_PINS);

        $arrs = array();

        $count = 0;

        foreach($temps as $temp) {

            $b = $temp - $account->getFBalance();

            if ($b > 0) {

                $arrs[$count] = $b;

                $count++;

            }

        }*/

        $this->arrs = $arrs;



		if($this->getRequestParameter('pinQty')>0 && $this->getRequestParameter('transactionPassword')<>""){

			if($this->getRequestParameter('ttlAmount')>$this->TblAccount->getFBalance()){

				$this->setFlash('errorMsg', "In-sufficient E-Cash");

	        }elseif($tbl_user->getFPassword2()<>$this->getRequestParameter('transactionPassword')){

	        	$this->setFlash('errorMsg', "Invalid transactionPassword password");

	        }elseif($this->getRequestParameter('pinQty')>0){

				$pin = $this->getRequestParameter('pinQty');

				$c = new Criteria();

		    	$c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_CPS);

		    	$TblSetting = TblSettingPeer::doSelectOne($c);

		    	if($TblSetting){ 

		    		$cps = $TblSetting->getFValue();

		    	}else{ 

		    		$cps = 0;

		    	}

				

				$datetime = date("Y/m/d h:i:s A");		

		        

		        while($pin>0){

                	$fpin = $this->generateFPin();

        

                    $newPin = new TblPin();

                    $newPin->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

                    $newPin->setFPin($fpin);

                    $newPin->setFCPS($cps);

                    $newPin->setFUnit('500');

                    $newPin->setFType(GLOBALS::ACCOUNT_LEDGER_ACTION_PURCHASE);

                    $newPin->setFCreatedBy($this->getUser()->getAttribute(Globals::SESSION_USERID));

                    $newPin->setFCreatedDatetime($datetime);

					$newPin->save();

					

                    --$pin;

                }

                

                $tbl_account_ledger = new TblAccountLedger();

	            $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_ECASH);

	            $tbl_account_ledger->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

	            $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_PURCHASE);

	            $tbl_account_ledger->setFCredit(0);

	            $tbl_account_ledger->setFDebit($this->getRequestParameter('ttlAmount'));

	            $tbl_account_ledger->setFBalance($this->TblAccount->getFBalance()-$this->getRequestParameter('ttlAmount'));

	            $tbl_account_ledger->setFCreatedDatetime($datetime);

	            $tbl_account_ledger->save();

	            $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);

                

                $c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

				$this->TblAccount = TblAccountPeer::doSelectOne($c);

			}	

		}

    }

    

    public function executeEcashLog(){

    	$this->title = "Finance";

    	$this->title2 = "E-Cash Log";

    	

    	/*$c = new Criteria();

    	$c->add(TblAccountLedgerPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

    	$c->addAnd(TblAccountLedgerPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

    	$c->addDescendingOrderByColumn(TblAccountLedgerPeer::F_CREATED_DATETIME);

    	$this->TblLedger = TblAccountLedgerPeer::doSelect($c);*/

    }



    public function executePinLog(){

    	$this->title = "Business";

    	$this->title2 = "Pin Transaction Log";

    	

    	/*$c = new Criteria();

    	$c->add(TblPinPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

    	$c->addDescendingOrderByColumn(TblPinPeer::F_CREATED_DATETIME);

    	$this->TblLedger = TblPinPeer::doSelect($c);*/

    }

    

    public function executeCertificate(){

    	$this->title = "Personal Profile";

    	$this->title2 = "Certificate";



        $tblDist = TblDistributorPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_DISTID));



        $cps = 0;

        $cpsSetting = 0;



        $c = new Criteria();

		$c->add(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_CPS);

		$exist = TblAccountPeer::doSelectOne($c);

		if($exist) $cps = $exist->getFBalance();



        $c = new Criteria();

        $c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_CPS);

        $TblSetting = TblSettingPeer::doSelectOne($c);

        if($TblSetting) $cpsSetting = $TblSetting->getFValue();



        $this->memberCode = $tblDist->getFCode();

        $this->memberName = "<U>".$tblDist->getFName()."</U>";

        $this->activationDate = "<U>".date('d-M-Y', strtotime($tblDist->getFActiveDatetime()))."</U>";



        $this->memberCps = $cps;

        $this->cps = $cpsSetting;



    }

    

    public function executeGoldRedemption()

    {

    	$this->title = "Finance";

    	$this->title2 = "Gold Redemption";

    	

    	$this->setFlash('errorMsg', "");

        $this->setFlash('successMsg', "");

    	$c = new Criteria();

		$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD);

		$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$this->TblAccount = TblAccountPeer::doSelectOne($c);

		

		$tbl_user = TblUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

		

		if($this->getRequestParameter('goldAmount')>0 && $this->getRequestParameter('transactionPassword')<>""){

			if($this->getRequestParameter('goldAmount')>$this->TblAccount->getFBalance()){

				$this->setFlash('errorMsg', "In-sufficient gold amount");

	        }elseif($tbl_user->getFPassword2()<>$this->getRequestParameter('transactionPassword')){

	        	$this->setFlash('errorMsg', "Invalid trx password");

	        }elseif($this->getRequestParameter('ecashAmount')>0){

				$datetime = date("Y/m/d h:i:s A");		

		        

		        $tbl_account_ledger = new TblAccountLedger();

	            $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_GOLD_DIVIDEND);

	            $tbl_account_ledger->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

	            $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_REDEEM);

	            $tbl_account_ledger->setFCredit(0);

	            $tbl_account_ledger->setFDebit($this->getRequestParameter('goldAmount'));

	            $tbl_account_ledger->setFBalance($this->TblAccount->getFBalance()-$this->getRequestParameter('goldAmount'));

	            $tbl_account_ledger->setFCreatedDatetime($datetime);

	            $tbl_account_ledger->save();

		        $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_GOLD_DIVIDEND);

		        

		        $tbl_gold_redeem = new TblGoldRedeem();

	            $tbl_gold_redeem->setFGold($this->getRequestParameter('goldAmount'));

	            $tbl_gold_redeem->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

	            $tbl_gold_redeem->setFStatus(Globals::STATUS_PENDING);

	            $tbl_gold_redeem->setFCreatedDatetime($datetime);

	            $tbl_gold_redeem->save();

		        

	            $this->setFlash('successMsg', "Redeem gold success");

	            

	            $c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

				$this->TblAccount = TblAccountPeer::doSelectOne($c);

			}	

		}

    }

    

    public function executeGoldWithdrawal()

    {

    	$this->title = "Finance";

    	$this->title2 = "Gold Withdrawal";

    	

    	$this->setFlash('errorMsg', "");

        $this->setFlash('successMsg', "");

    	$c = new Criteria();

		$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD);

		$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$this->TblAccount = TblAccountPeer::doSelectOne($c);

		

		$tbl_user = TblUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

		

		if($this->getRequestParameter('goldAmount')>0 && $this->getRequestParameter('transactionPassword')<>""){

			if($this->getRequestParameter('goldAmount')>$this->TblAccount->getFBalance()){

				$this->setFlash('errorMsg', "In-sufficient gold amount");

	        }elseif($tbl_user->getFPassword2()<>$this->getRequestParameter('transactionPassword')){

	        	$this->setFlash('errorMsg', "Invalid trx password");

	        }else{

				$c = new Criteria();

				$c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_GOLD_PRICE);

				$TblSetting = TblSettingPeer::doSelectOne($c);

				if($TblSetting){ 

					$gold_price = $TblSetting->getFValue();

				}else{ 

					$gold_price = 0;

				}

				

				if($gold_price<=10){

					$this->setFlash('errorMsg', "System cannot get gold price, please try again");

				}else{				

					$datetime = date("Y/m/d h:i:s A");		

			        

			        $tbl_account_ledger = new TblAccountLedger();

		            $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_GOLD);

		            $tbl_account_ledger->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

		            $tbl_account_ledger->setFAction("sell gold dividend");

		            $tbl_account_ledger->setFCredit(0);

		            $tbl_account_ledger->setFDebit($this->getRequestParameter('goldAmount'));

		            $tbl_account_ledger->setFBalance($this->TblAccount->getFBalance()-$this->getRequestParameter('goldAmount'));

		            $tbl_account_ledger->setFCreatedDatetime($datetime);

		            $tbl_account_ledger->save();

			        $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_GOLD);

			        

			        $tbl_gold_withdraw = new TblGoldWithdraw();

		            $tbl_gold_withdraw->setFGold($this->getRequestParameter('goldAmount'));

		            $tbl_gold_withdraw->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

		            $tbl_gold_withdraw->setFGoldPrice($gold_price);

		            $amount = $this->format2decimal($this->getRequestParameter('goldAmount') * $gold_price);

		            $tbl_gold_withdraw->setFAmount($amount);

		            $tbl_gold_withdraw->setFCreatedDatetime($datetime);

		            $tbl_gold_withdraw->save();

			        

			        $c = new Criteria();

					$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

					$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

					$ecash = TblAccountPeer::doSelectOne($c);

			        

			        $tbl_account_ledger = new TblAccountLedger();

		            $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_ECASH);

		            $tbl_account_ledger->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

		            $tbl_account_ledger->setFAction("sell gold dividend");

		            $tbl_account_ledger->setFCredit($amount);

		            $tbl_account_ledger->setFDebit(0);

		            $tbl_account_ledger->setFBalance($ecash->getFBalance()+$amount);

		            $tbl_account_ledger->setFCreatedDatetime($datetime);

		            $tbl_account_ledger->save();

			        $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);

			        

		            $this->setFlash('successMsg', "Withdraw gold success");

		            

		            $c = new Criteria();

					$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD);

					$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

					$this->TblAccount = TblAccountPeer::doSelectOne($c);

				}

			}	

		}

    }

    

    public function executeEcashWithdrawal()

    {

    	$this->title = "Finance";

    	$this->title2 = "E-Cash Withdrawal";

    	$this->setFlash('errorMsg', "");

        $this->setFlash('successMsg', "");

    	$c = new Criteria();

		$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

		$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

		$this->TblAccount = TblAccountPeer::doSelectOne($c);

		

		$tbl_user = TblUserPeer::retrieveByPk($this->getUser()->getAttribute(Globals::SESSION_USERID));

		

		if($this->getRequestParameter('ecashAmount')>0 && $this->getRequestParameter('transactionPassword')<>""){

			if($this->getRequestParameter('ecashAmount')>$this->TblAccount->getFBalance()){

				$this->setFlash('errorMsg', "In-sufficient ecash amount");

	        }elseif($tbl_user->getFPassword2()<>$this->getRequestParameter('transactionPassword')){

	        	$this->setFlash('errorMsg', "Invalid trx password");

	        }elseif($this->getRequestParameter('ecashAmount')>0){

				$datetime = date("Y/m/d h:i:s A");		

			        

			    $tbl_account_ledger = new TblAccountLedger();

		        $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_ECASH);

		        $tbl_account_ledger->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

		        $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_WITHDRAWAL);

		        $tbl_account_ledger->setFCredit(0);

		        $tbl_account_ledger->setFDebit($this->getRequestParameter('ecashAmount'));

		        $tbl_account_ledger->setFBalance($this->TblAccount->getFBalance()-$this->getRequestParameter('ecashAmount'));

		        $tbl_account_ledger->setFCreatedDatetime($datetime);

		        $tbl_account_ledger->save();

			    $this->revalidateAccount($this->getUser()->getAttribute(Globals::SESSION_DISTID), Globals::ACCOUNT_TYPE_ECASH);

			        

			    $tbl_ecash_withdraw = new TblEcashWithdraw();

		        $tbl_ecash_withdraw->setFDistId($this->getUser()->getAttribute(Globals::SESSION_DISTID));

		        $tbl_ecash_withdraw->setFDeduct($this->getRequestParameter('ecashDeduct'));

		        $tbl_ecash_withdraw->setFAmount($this->getRequestParameter('ecashAmount'));

		        $tbl_ecash_withdraw->setFStatus(Globals::STATUS_PENDING);

		        $tbl_ecash_withdraw->setFCreatedDatetime($datetime);

		        $tbl_ecash_withdraw->save();

			     

		        $this->setFlash('successMsg', "Withdraw ecash success");

		            

		        $c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

				$this->TblAccount = TblAccountPeer::doSelectOne($c);

			}	

		}

    }

    

    public function executeBdetails()

    {

    	$this->title = "Finance";

    	$this->title2 = "Bonus Details";

    	$this->bonus = $this->getRequestParameter('bonus');

    	//print_r($this->getRequestParameter('bonus').$this->getUser()->getAttribute(Globals::SESSION_USERID));

    	$c = new Criteria();

    	$c->add(TblMemberCommPeer::F_DIST_ID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

    	$c->addAnd(TblMemberCommPeer::F_TYPE, $this->getRequestParameter('bonus'));

    	

		$this->TblBonus = TblMemberCommPeer::doSelect($c);

    }

    

    public function executeBonusDetails()

    {

    	$this->title = "Finance";

    	$this->title2 = "Bonus Details";

    	/*

    	$c = new Criteria();

    	$c->add(TblMemberCommSumPeer::F_DIST_ID,$this->getUser()->getAttribute(Globals::SESSION_USERID));

    	if($this->getRequestParameter('date_from')<>"")

    		$c->add(TblMemberCommSumPeer::F_BONUS_DATE,$this->getRequestParameter('date_from'), Criteria::GREATER_EQUAL);

		if($this->getRequestParameter('date_to')<>"")

    		$c->add(TblMemberCommSumPeer::F_BONUS_DATE,$this->getRequestParameter('date_to'), Criteria::LESS_EQUAL);

    	 */

    	$query = "SELECT SUM(f_dsb) AS f_dsb, SUM(f_gdb) AS f_gdb, SUM(f_gap) AS f_gap, SUM(f_elb) AS f_elb, SUM(f_wpb) AS f_wpb, SUM(f_dsb+f_gdb+f_gap+f_elb+f_wpb) AS f_total FROM tbl_member_comm_sum WHERE f_dist_id=".$this->getUser()->getAttribute(Globals::SESSION_DISTID); 

		if($this->getRequestParameter('date_from')<>""){

    		$query .= " AND f_bonus_date>='".$this->getRequestParameter('date_from')."'";

    		$this->date_from = $this->getRequestParameter('date_from');

		}

		if($this->getRequestParameter('date_to')<>""){

    		$query .= " AND f_bonus_date<='".$this->getRequestParameter('date_to')."'";

    		$this->date_to = $this->getRequestParameter('date_to');

		}

    	$query .= " GROUP BY f_dist_id";

		$connection = Propel::getConnection();

		$statement = $connection->prepareStatement($query);

		$rs = $statement->executeQuery();

		if ($rs->next()) {

			$arr = $rs->getRow();

			$this->dsb = number_format($arr['f_dsb'],2);

			$this->gdb = number_format($arr['f_gdb'],2);

			$this->gap = number_format($arr['f_gap'],2);

			$this->elb = number_format($arr['f_elb'],2);

			$this->wpb = number_format($arr['f_wpb'],2);

			$this->total = number_format($arr['f_total'],2); 			

		}else{

			$this->dsb = number_format(0,2);

			$this->gdb = number_format(0,2);

			$this->gap = number_format(0,2);

			$this->elb = number_format(0,2);

			$this->wpb = number_format(0,2);

			$this->total = number_format(0,2);

		}

    }

    

    public function executeSponsorTree()

    {

    	$this->title = "Genealogy";

    	$this->title2 = "Sponsor Tree";

    	

    	$id = $this->getUser()->getAttribute(Globals::SESSION_DISTID);

    	$distinfo = TblDistributorPeer::retrieveByPk($id);

        $this->distinfo = $distinfo;

        $this->hasChild = $this->checkHasChild($distinfo->getFId());



    	//if($this->getRequestParameter('id')>0)

    	//	$this->user = TblDistributorPeer::retrieveByPk($this->getRequestParameter('id'));

    	

    	//$this->downline_node = $this->retrieve_gen_downline($id, 'f_parentid', 'gen_tree', 1);

    }

    public function executeManipulateSponsorTree()

    {

        $parentId = $this->getRequestParameter('root');

        $arrTree = array();

        if ($parentId != "") {

            $c = new Criteria();

            $c->add(TblDistributorPeer::F_PARENTID, $parentId);

            $c->addAnd(TblDistributorPeer::F_STATUS, Globals::STATUS_ACTIVE);

            $dists = TblDistributorPeer::doSelect($c);



            $idx = 0;

            foreach($dists as $dist)

            {

                $arrTree[$idx]["text"] = $dist->getFCode()." ".$dist->getFNickName()." Joined ".date('Y-m-d', strtotime($dist->getFActiveDatetime()));;

                $arrTree[$idx]["id"] = $dist->getFId();

                $arrTree[$idx]["hasChildren"] = $this->checkHasChild($dist->getFId());

                $idx++;

            }

        }



        echo json_encode($arrTree);



        return sfView::HEADER_ONLY;

    }

    public function executePlacementTree()

    {

    	$this->title = "Genealogy";

    	$this->title2 = "Placement Tree";

    	

    	$c = new Criteria();

		$c->add(TblDistributorPeer::F_LEFT2, '0');

		$c->addAnd(TblDistributorPeer::F_PARENTID2, '0', Criteria::GREATER_THAN);

		$c->addAnd(TblDistributorPeer::F_STATUS, Globals::STATUS_ACTIVE);

		$exist = TblDistributorPeer::doSelect($c);

			

		if($exist){

			$this->rebuildplacement();

		}

    	

		$code=$this->getUser()->getAttribute(Globals::SESSION_USERNAME);



		if($this->getRequestParameter('distcode')) {

			

			$query = "SELECT b.f_code, c.f_code AS scode FROM tbl_distributor a INNER JOIN tbl_distributor b ON b.f_left2 between a.f_left2 AND a.f_right2 AND a.f_code='".$code."' AND b.f_code='".htmlspecialchars($this->getRequestParameter('distcode'),ENT_QUOTES)."' INNER JOIN tbl_distributor c ON b.f_parentid2=c.f_id";

			$connection = Propel::getConnection();

		    $statement = $connection->prepareStatement($query);

		    $rs = $statement->executeQuery();

		    

		    if ($rs->next()) {

            	$arr = $rs->getRow();

            	if($code!=$arr["f_code"])

            		$scode=$arr["scode"];

            	$code=$arr["f_code"];

		    } else {

		    	return $this->redirect('/member/placementTree');

		    }

		    

		    $code = $this->getRequestParameter('distcode');

		    $this->search_code = $code;

		}



		$anode=array(0=>array(),1=>array(),2=>array(),3=>array(),4=>array(),5=>array(),6=>array());

		for($clevel=0;$clevel<4;$clevel++) {

			switch($clevel) {

			case 0;

				$c = new Criteria();

				$c->add(TblDistributorPeer::F_CODE, $code);

				$rs = TblDistributorPeer::doSelectOne($c);

				$anode[0]['f_id']=$rs->getFId();

				$anode[0]['f_code']=$rs->getFCode();

				$anode[0]['f_nickname']=$rs->getFNickname();

				$anode[0]['f_active_datetime']=$rs->getFActiveDatetime();

				$anode[0]['f_leg2']=$rs->getFLeg2();				

				

				$c = new Criteria();

				$c->add(TblAccountPeer::F_TYPE,Globals::ACCOUNT_TYPE_CPS);

				$c->addAnd(TblAccountPeer::F_DIST_ID, $rs->getFId());

				$cps = TblAccountPeer::doSelectOne($c);

				$anode[0]['f_cps']="CPS: ".$cps->getFBalance();

				break;

			case 1;

				$apos=array(0=>array(),1=>array());

				$aext=array();

				if(sizeof($anode[0])) {

					$c = new Criteria();

					$c->add(TblDistributorPeer::F_PARENTID2, $anode[0]['f_id']);

					$c->addAscendingOrderByColumn(TblDistributorPeer::F_LEG2);

					$TblDist1 = TblDistributorPeer::doSelect($c);

					

					foreach($TblDist1 as $rs) {

						$c = new Criteria();

						$c->add(TblAccountPeer::F_TYPE,Globals::ACCOUNT_TYPE_CPS);

						$c->addAnd(TblAccountPeer::F_DIST_ID, $rs->getFId());

						$cps = TblAccountPeer::doSelectOne($c);

						

						if(sizeof($apos[$rs->getFLeg2()])) {

							//$aext[]=$rs;

							$aext[]['f_id']=$rs->getFId();

							$aext[]['f_code']=$rs->getFCode();

							$aext[]['f_nickname']=$rs->getFNickname();

							$aext[]['f_active_datetime']=$rs->getFActiveDatetime();

							$aext[]['f_leg2']=$rs->getFLeg2();

							$aext[]['f_cps']="CPS: ".$cps->getFBalance();

						} else {

							//$apos[$rs->getFLeg2()]=$rs;

							$apos[$rs->getFLeg2()]['f_id']=$rs->getFId();

							$apos[$rs->getFLeg2()]['f_code']=$rs->getFCode();

							$apos[$rs->getFLeg2()]['f_nickname']=$rs->getFNickname();

							$apos[$rs->getFLeg2()]['f_active_datetime']=$rs->getFActiveDatetime();

							$apos[$rs->getFLeg2()]['f_leg2']=$rs->getFLeg2();

							$apos[$rs->getFLeg2()]['f_cps']="CPS: ".$cps->getFBalance();

						}

					}

					if(sizeof($aext))

					foreach($aext as $key=>$value) {

						foreach($apos as $pkey=>$pvalue) {

							if(!sizeof($pvalue)) {

								$apos[$pkey]=$value;

								break;

							}

						}

					}

					foreach($apos as $key=>$value) {

						$id = $anode[0]["f_id"];

						$c = new Criteria();

						$c->add(TblDistributorPeer::F_PARENTID2, $id);

						$placements = TblDistributorPeer::doSelect($c);

						

						$left_cf = 0;

						$right_cf = 0;

						$left_mcf = 0;

						$right_mcf = 0;

						$cf_amount = 0;

						foreach($placements as $placement){

							$c = new Criteria();

							$c->add(TblPointCfPeer::F_DIST_ID, $placement->getFId());

							$c->addDescendingOrderByColumn(TblPointCfPeer::F_DATE);

							$cf = TblPointCfPeer::doSelectOne($c);

							if($cf) $cf_amount = $cf->getFCf();

							

							$query = "SELECT SUM(f_gs) AS f_gs FROM tbl_point_cf WHERE f_date between '".date('Y-m')."-01' AND '".date('Y-m')."-31' AND f_dist_id=".$placement->getFId()." GROUP BY f_dist_id"; 

							$connection = Propel::getConnection();

							$statement = $connection->prepareStatement($query);

			    			$rs = $statement->executeQuery();

			    						    											

							if($placement->getFLeg2()==1){

								$left_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $left_mcf= $arr["f_gs"];

						        }

							}

							if($placement->getFLeg2()==2){

								$right_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $right_mcf= $arr["f_gs"];

						        }

							}

						}

						

						$anode[0]["f_pv"]="Carry Forward CPS: ".number_format($left_cf,0)." | ".number_format($right_cf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair where f_distributor_id=".$anode[0]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[0]["f_pv"].=$rs->fields["f_pv"];

							else $anode[0]["f_pv"].="0";

						} else $anode[0]["f_pv"].="0"; */

						$anode[0]["f_pv2"]="This month CPS: ".number_format($left_mcf,0)." | ".number_format($right_mcf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair2 where f_distributor_id=".$anode[0]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[0]["f_pv2"].=$rs->fields["f_pv"];

							else $anode[0]["f_pv2"].="0";

						} else $anode[0]["f_pv2"].="0";*/

					}

				}

				$anode[1]=$apos[1];

				$anode[2]=$apos[2];

				break;

			case 2;

				$apos=array(0=>array(),1=>array());

				$aext=array();

				if(sizeof($anode[1])) {

					$c = new Criteria();

					$c->add(TblDistributorPeer::F_PARENTID2, $anode[1]['f_id']);

					$c->addAscendingOrderByColumn(TblDistributorPeer::F_LEG2);

					$TblDist2 = TblDistributorPeer::doSelect($c);

					

					foreach($TblDist2 as $rs) {

						$c = new Criteria();

						$c->add(TblAccountPeer::F_TYPE,Globals::ACCOUNT_TYPE_CPS);

						$c->addAnd(TblAccountPeer::F_DIST_ID, $rs->getFId());

						$cps = TblAccountPeer::doSelectOne($c);

						

						if(sizeof($apos[$rs->getFLeg2()])) {

							//$aext[]=$rs;

							$aext[]['f_id']=$rs->getFId();

							$aext[]['f_code']=$rs->getFCode();

							$aext[]['f_nickname']=$rs->getFNickname();

							$aext[]['f_active_datetime']=$rs->getFActiveDatetime();

							$aext[]['f_leg2']=$rs->getFLeg2();

							$aext[]['f_cps']="CPS: ".$cps->getFBalance();

						} else {

							//$apos[$rs->getFLeg2()]=$rs;

							$apos[$rs->getFLeg2()]['f_id']=$rs->getFId();

							$apos[$rs->getFLeg2()]['f_code']=$rs->getFCode();

							$apos[$rs->getFLeg2()]['f_nickname']=$rs->getFNickname();

							$apos[$rs->getFLeg2()]['f_active_datetime']=$rs->getFActiveDatetime();

							$apos[$rs->getFLeg2()]['f_leg2']=$rs->getFLeg2();

							$apos[$rs->getFLeg2()]['f_cps']="CPS: ".$cps->getFBalance();

						}

					}

					if(sizeof($aext))

					foreach($aext as $key=>$value) {

						foreach($apos as $pkey=>$pvalue) {

							if(!sizeof($pvalue)) {

								$apos[$pkey]=$value;

								break;

							}

						}

					}

					foreach($apos as $key=>$value) {

						$id = $anode[1]["f_id"];

						$c = new Criteria();

						$c->add(TblDistributorPeer::F_PARENTID2, $id);

						$placements = TblDistributorPeer::doSelect($c);

						

						$left_cf = 0;

						$right_cf = 0;

						$left_mcf = 0;

						$right_mcf = 0;

						$cf_amount = 0;

						foreach($placements as $placement){

							$c = new Criteria();

							$c->add(TblPointCfPeer::F_DIST_ID, $placement->getFId());

							$c->addDescendingOrderByColumn(TblPointCfPeer::F_DATE);

							$cf = TblPointCfPeer::doSelectOne($c);

							if($cf) $cf_amount = $cf->getFCf();

							

							$query = "SELECT SUM(f_gs) AS f_gs FROM tbl_point_cf WHERE f_date between '".date('Y-m')."-01' AND '".date('Y-m')."-31' AND f_dist_id=".$placement->getFId()." GROUP BY f_dist_id"; 

							$connection = Propel::getConnection();

							$statement = $connection->prepareStatement($query);

			    			$rs = $statement->executeQuery();

			    						    											

							if($placement->getFLeg2()==1){

								$left_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $left_mcf= $arr["f_gs"];

						        }

							}

							if($placement->getFLeg2()==2){

								$right_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $right_mcf= $arr["f_gs"];

						        }

							}

						}

						

						$anode[1]["f_pv"]="Carry Forward CPS: ".number_format($left_cf,0)." | ".number_format($right_cf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair where f_distributor_id=".$anode[1]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[1]["f_pv"].=$rs->fields["f_pv"];

							else $anode[1]["f_pv"].="0";

						} else $anode[1]["f_pv"].="0";*/

						$anode[1]["f_pv2"]="This Month CPS: ".number_format($left_mcf,0)." | ".number_format($right_mcf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair2 where f_distributor_id=".$anode[1]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[1]["f_pv2"].=$rs->fields["f_pv"];

							else $anode[1]["f_pv2"].="0";

						} else $anode[1]["f_pv2"].="0";*/

					}

				}

				$anode[3]=$apos[1];

				$anode[4]=$apos[2];



				$apos=array(0=>array(),1=>array());

				$aext=array();

				if(sizeof($anode[2])) {

					$c = new Criteria();

					$c->add(TblDistributorPeer::F_PARENTID2, $anode[2]['f_id']);

					$c->addAscendingOrderByColumn(TblDistributorPeer::F_LEG2);

					$TblDist3 = TblDistributorPeer::doSelect($c);

					

					foreach($TblDist3 as $rs) {

						$c = new Criteria();

						$c->add(TblAccountPeer::F_TYPE,Globals::ACCOUNT_TYPE_CPS);

						$c->addAnd(TblAccountPeer::F_DIST_ID, $rs->getFId());

						$cps = TblAccountPeer::doSelectOne($c);

						

						if(sizeof($apos[$rs->getFLeg2()])) {

							//$aext[]=$rs;

							$aext[]['f_id']=$rs->getFId();

							$aext[]['f_code']=$rs->getFCode();

							$aext[]['f_nickname']=$rs->getFNickname();

							$aext[]['f_active_datetime']=$rs->getFActiveDatetime();

							$aext[]['f_leg2']=$rs->getFLeg2();

							$aext[]['f_cps']="CPS: ".$cps->getFBalance();

						} else {

							//$apos[$rs->getFLeg2()]=$rs;

							$apos[$rs->getFLeg2()]['f_id']=$rs->getFId();

							$apos[$rs->getFLeg2()]['f_code']=$rs->getFCode();

							$apos[$rs->getFLeg2()]['f_nickname']=$rs->getFNickname();

							$apos[$rs->getFLeg2()]['f_active_datetime']=$rs->getFActiveDatetime();

							$apos[$rs->getFLeg2()]['f_leg2']=$rs->getFLeg2();

							$apos[$rs->getFLeg2()]['f_cps']="CPS: ".$cps->getFBalance();

						}

					}

					if(sizeof($aext))

					foreach($aext as $key=>$value) {

						foreach($apos as $pkey=>$pvalue) {

							if(!sizeof($pvalue)) {

								$apos[$pkey]=$value;

								break;

							}

						}

					}

					foreach($apos as $key=>$value) {

						$id = $anode[2]["f_id"];

						$c = new Criteria();

						$c->add(TblDistributorPeer::F_PARENTID2, $id);

						$placements = TblDistributorPeer::doSelect($c);

						

						$left_cf = 0;

						$right_cf = 0;

						$left_mcf = 0;

						$right_mcf = 0;

						$cf_amount = 0;

						foreach($placements as $placement){

							$c = new Criteria();

							$c->add(TblPointCfPeer::F_DIST_ID, $placement->getFId());

							$c->addDescendingOrderByColumn(TblPointCfPeer::F_DATE);

							$cf = TblPointCfPeer::doSelectOne($c);

							if($cf) $cf_amount = $cf->getFCf();

							

							$query = "SELECT SUM(f_gs) AS f_gs FROM tbl_point_cf WHERE f_date between '".date('Y-m')."-01' AND '".date('Y-m')."-31' AND f_dist_id=".$placement->getFId()." GROUP BY f_dist_id"; 

							$connection = Propel::getConnection();

							$statement = $connection->prepareStatement($query);

			    			$rs = $statement->executeQuery();

			    						    											

							if($placement->getFLeg2()==1){

								$left_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $left_mcf= $arr["f_gs"];

						        }

							}

							if($placement->getFLeg2()==2){

								$right_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $right_mcf= $arr["f_gs"];

						        }

							}

						}

						

						$anode[2]["f_pv"]="Carry Forward CPS: ".number_format($left_cf,0)." | ".number_format($right_cf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair where f_distributor_id=".$anode[2]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[2]["f_pv"].=$rs->fields["f_pv"];

							else $anode[2]["f_pv"].="0";

						} else $anode[2]["f_pv"].="0";*/

						$anode[2]["f_pv2"]="This Month CPS: ".number_format($left_mcf,0)." | ".number_format($right_mcf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair2 where f_distributor_id=".$anode[2]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[2]["f_pv2"].=$rs->fields["f_pv"];

							else $anode[2]["f_pv2"].="0";

						} else $anode[2]["f_pv2"].="0";*/

					}

				}

				$anode[5]=$apos[1];

				$anode[6]=$apos[2];



				break;

			case 3;

				$apos=array(0=>array(),1=>array());

				$aext=array();

				if(sizeof($anode[3])) {

					$c = new Criteria();

					$c->add(TblDistributorPeer::F_PARENTID2, $anode[3]['f_id']);

					$c->addAscendingOrderByColumn(TblDistributorPeer::F_LEG2);

					$TblDist3 = TblDistributorPeer::doSelect($c);

					

					foreach($TblDist3 as $rs) {

						$c = new Criteria();

						$c->add(TblAccountPeer::F_TYPE,Globals::ACCOUNT_TYPE_CPS);

						$c->addAnd(TblAccountPeer::F_DIST_ID, $rs->getFId());

						$cps = TblAccountPeer::doSelectOne($c);

						

						if(sizeof($apos[$rs->getFLeg2()])) {

							//$aext[]=$rs;

							$aext[]['f_id']=$rs->getFId();

							$aext[]['f_code']=$rs->getFCode();

							$aext[]['f_nickname']=$rs->getFNickname();

							$aext[]['f_active_datetime']=$rs->getFActiveDatetime();

							$aext[]['f_leg2']=$rs->getFLeg2();

							$aext[]['f_cps']="CPS: ".$cps->getFBalance();

						} else {

							//$apos[$rs->getFLeg2()]=$rs;

							$apos[$rs->getFLeg2()]['f_id']=$rs->getFId();

							$apos[$rs->getFLeg2()]['f_code']=$rs->getFCode();

							$apos[$rs->getFLeg2()]['f_nickname']=$rs->getFNickname();

							$apos[$rs->getFLeg2()]['f_active_datetime']=$rs->getFActiveDatetime();

							$apos[$rs->getFLeg2()]['f_leg2']=$rs->getFLeg2();

							$apos[$rs->getFLeg2()]['f_cps']="CPS: ".$cps->getFBalance();

						}

					}					

					if(sizeof($aext))

					foreach($aext as $key=>$value) {

						foreach($apos as $pkey=>$pvalue) {

							if(!sizeof($pvalue)) {

								$apos[$pkey]=$value;

								break;

							}

						}

					}

					foreach($apos as $key=>$value) {

						$id = $anode[3]["f_id"];

						$c = new Criteria();

						$c->add(TblDistributorPeer::F_PARENTID2, $id);

						$placements = TblDistributorPeer::doSelect($c);

						

						$left_cf = 0;

						$right_cf = 0;

						$left_mcf = 0;

						$right_mcf = 0;

						$cf_amount = 0;

						foreach($placements as $placement){

							$c = new Criteria();

							$c->add(TblPointCfPeer::F_DIST_ID, $placement->getFId());

							$c->addDescendingOrderByColumn(TblPointCfPeer::F_DATE);

							$cf = TblPointCfPeer::doSelectOne($c);

							if($cf) $cf_amount = $cf->getFCf();

							

							$query = "SELECT SUM(f_gs) AS f_gs FROM tbl_point_cf WHERE f_date between '".date('Y-m')."-01' AND '".date('Y-m')."-31' AND f_dist_id=".$placement->getFId()." GROUP BY f_dist_id"; 

							$connection = Propel::getConnection();

							$statement = $connection->prepareStatement($query);

			    			$rs = $statement->executeQuery();

			    						    											

							if($placement->getFLeg2()==1){

								$left_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $left_mcf= $arr["f_gs"];

						        }

							}

							if($placement->getFLeg2()==2){

								$right_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $right_mcf= $arr["f_gs"];

						        }

							}

						}

						

						$anode[3]["f_pv"]="Carry Forward CPS: ".number_format($left_cf,0)." | ".number_format($right_cf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair where f_distributor_id=".$anode[3]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[4]["f_pv"].=$rs->fields["f_pv"];

							else $anode[3]["f_pv"].="0";

						} else $anode[3]["f_pv"].="0";*/

						$anode[3]["f_pv2"]="This Month CPS: ".number_format($left_mcf,0)." | ".number_format($right_mcf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair2 where f_distributor_id=".$anode[3]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[3]["f_pv2"].=$rs->fields["f_pv"];

							else $anode[3]["f_pv2"].="0";

						} else $anode[3]["f_pv2"].="0";*/

					}

				}



				$apos=array(0=>array(),1=>array());

				$aext=array();

				if(sizeof($anode[4])) {

					$c = new Criteria();

					$c->add(TblDistributorPeer::F_PARENTID2, $anode[4]['f_id']);

					$c->addAscendingOrderByColumn(TblDistributorPeer::F_LEG2);

					$TblDist3 = TblDistributorPeer::doSelect($c);

					

					foreach($TblDist3 as $rs) {

						$c = new Criteria();
						$c->add(TblAccountPeer::F_TYPE,Globals::ACCOUNT_TYPE_CPS);

						$c->addAnd(TblAccountPeer::F_DIST_ID, $rs->getFId());

						$cps = TblAccountPeer::doSelectOne($c);

						

						if(sizeof($apos[$rs->getFLeg2()])) {

							//$aext[]=$rs;

							$aext[]['f_id']=$rs->getFId();

							$aext[]['f_code']=$rs->getFCode();

							$aext[]['f_nickname']=$rs->getFNickname();

							$aext[]['f_active_datetime']=$rs->getFActiveDatetime();

							$aext[]['f_leg2']=$rs->getFLeg2();

							$aext[]['f_cps']="CPS: ".$cps->getFBalance();

						} else {

							//$apos[$rs->getFLeg2()]=$rs;

							$apos[$rs->getFLeg2()]['f_id']=$rs->getFId();

							$apos[$rs->getFLeg2()]['f_code']=$rs->getFCode();

							$apos[$rs->getFLeg2()]['f_nickname']=$rs->getFNickname();

							$apos[$rs->getFLeg2()]['f_active_datetime']=$rs->getFActiveDatetime();

							$apos[$rs->getFLeg2()]['f_leg2']=$rs->getFLeg2();

							$apos[$rs->getFLeg2()]['f_cps']="CPS: ".$cps->getFBalance();

						}

					}

					if(sizeof($aext))

					foreach($aext as $key=>$value) {

						foreach($apos as $pkey=>$pvalue) {

							if(!sizeof($pvalue)) {

								$apos[$pkey]=$value;

								break;

							}

						}

					}

					foreach($apos as $key=>$value) {

						$id = $anode[4]["f_id"];

						$c = new Criteria();

						$c->add(TblDistributorPeer::F_PARENTID2, $id);

						$placements = TblDistributorPeer::doSelect($c);

						

						$left_cf = 0;

						$right_cf = 0;

						$left_mcf = 0;

						$right_mcf = 0;

						$cf_amount = 0;

						foreach($placements as $placement){

							$c = new Criteria();

							$c->add(TblPointCfPeer::F_DIST_ID, $placement->getFId());

							$c->addDescendingOrderByColumn(TblPointCfPeer::F_DATE);

							$cf = TblPointCfPeer::doSelectOne($c);

							if($cf) $cf_amount = $cf->getFCf();

							

							$query = "SELECT SUM(f_gs) AS f_gs FROM tbl_point_cf WHERE f_date between '".date('Y-m')."-01' AND '".date('Y-m')."-31' AND f_dist_id=".$placement->getFId()." GROUP BY f_dist_id"; 

							$connection = Propel::getConnection();

							$statement = $connection->prepareStatement($query);

			    			$rs = $statement->executeQuery();

			    						    											

							if($placement->getFLeg2()==1){

								$left_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $left_mcf= $arr["f_gs"];

						        }

							}

							if($placement->getFLeg2()==2){

								$right_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $right_mcf= $arr["f_gs"];

						        }

							}

						}

						

						$anode[4]["f_pv"]="Carry Forward CPS: ".number_format($left_cf,0)." | ".number_format($right_cf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair where f_distributor_id=".$anode[4]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[4]["f_pv"].=$rs->fields["f_pv"];

							else $anode[4]["f_pv"].="0";

						} else $anode[4]["f_pv"].="0";*/

						$anode[4]["f_pv2"]="This Month CPS: ".number_format($left_mcf,0)." | ".number_format($right_mcf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair2 where f_distributor_id=".$anode[4]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[4]["f_pv2"].=$rs->fields["f_pv"];

							else $anode[4]["f_pv2"].="0";

						} else $anode[4]["f_pv2"].="0";*/

					}

				}



				$apos=array(0=>array(),1=>array());

				$aext=array();

				if(sizeof($anode[5])) {

					$c = new Criteria();

					$c->add(TblDistributorPeer::F_PARENTID2, $anode[5]['f_id']);

					$c->addAscendingOrderByColumn(TblDistributorPeer::F_LEG2);

					$TblDist3 = TblDistributorPeer::doSelect($c);

					

					foreach($TblDist3 as $rs) {

						$c = new Criteria();

						$c->add(TblAccountPeer::F_TYPE,Globals::ACCOUNT_TYPE_CPS);

						$c->addAnd(TblAccountPeer::F_DIST_ID, $rs->getFId());

						$cps = TblAccountPeer::doSelectOne($c);

						

						if(sizeof($apos[$rs->getFLeg2()])) {

							//$aext[]=$rs;

							$aext[]['f_id']=$rs->getFId();

							$aext[]['f_code']=$rs->getFCode();

							$aext[]['f_nickname']=$rs->getFNickname();

							$aext[]['f_active_datetime']=$rs->getFActiveDatetime();

							$aext[]['f_leg2']=$rs->getFLeg2();

							$aext[]['f_cps']="CPS: ".$cps->getFBalance();

						} else {

							//$apos[$rs->getFLeg2()]=$rs;

							$apos[$rs->getFLeg2()]['f_id']=$rs->getFId();

							$apos[$rs->getFLeg2()]['f_code']=$rs->getFCode();

							$apos[$rs->getFLeg2()]['f_nickname']=$rs->getFNickname();

							$apos[$rs->getFLeg2()]['f_active_datetime']=$rs->getFActiveDatetime();

							$apos[$rs->getFLeg2()]['f_leg2']=$rs->getFLeg2();

							$apos[$rs->getFLeg2()]['f_cps']="CPS: ".$cps->getFBalance();

						}

					}					

					if(sizeof($aext))

					foreach($aext as $key=>$value) {

						foreach($apos as $pkey=>$pvalue) {

							if(!sizeof($pvalue)) {

								$apos[$pkey]=$value;

								break;

							}

						}

					}

					foreach($apos as $key=>$value) {

						$id = $anode[5]["f_id"];

						$c = new Criteria();

						$c->add(TblDistributorPeer::F_PARENTID2, $id);

						$placements = TblDistributorPeer::doSelect($c);

						

						$left_cf = 0;

						$right_cf = 0;

						$left_mcf = 0;

						$right_mcf = 0;

						$cf_amount = 0;

						foreach($placements as $placement){

							$c = new Criteria();

							$c->add(TblPointCfPeer::F_DIST_ID, $placement->getFId());

							$c->addDescendingOrderByColumn(TblPointCfPeer::F_DATE);

							$cf = TblPointCfPeer::doSelectOne($c);

							if($cf) $cf_amount = $cf->getFCf();

							

							$query = "SELECT SUM(f_gs) AS f_gs FROM tbl_point_cf WHERE f_date between '".date('Y-m')."-01' AND '".date('Y-m')."-31' AND f_dist_id=".$placement->getFId()." GROUP BY f_dist_id"; 

							$connection = Propel::getConnection();

							$statement = $connection->prepareStatement($query);

			    			$rs = $statement->executeQuery();

			    						    											

							if($placement->getFLeg2()==1){

								$left_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $left_mcf= $arr["f_gs"];

						        }

							}

							if($placement->getFLeg2()==2){

								$right_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $right_mcf= $arr["f_gs"];

						        }

							}

						}

						

						$anode[5]["f_pv"]="Carry Forward CPS: ".number_format($left_cf,0)." | ".number_format($right_cf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair where f_distributor_id=".$anode[5]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[4]["f_pv"].=$rs->fields["f_pv"];

							else $anode[5]["f_pv"].="0";

						} else $anode[5]["f_pv"].="0";*/

						$anode[5]["f_pv2"]="This Month CPS: ".number_format($left_mcf,0)." | ".number_format($right_mcf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair2 where f_distributor_id=".$anode[5]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[4]["f_pv2"].=$rs->fields["f_pv"];

							else $anode[5]["f_pv2"].="0";

						} else $anode[5]["f_pv2"].="0";*/

					}

				}



				$apos=array(0=>array(),1=>array());

				$aext=array();

				if(sizeof($anode[6])) {

					$c = new Criteria();

					$c->add(TblDistributorPeer::F_PARENTID2, $anode[6]['f_id']);

					$c->addAscendingOrderByColumn(TblDistributorPeer::F_LEG2);

					$TblDist3 = TblDistributorPeer::doSelect($c);

					

					foreach($TblDist3 as $rs) {

						$c = new Criteria();

						$c->add(TblAccountPeer::F_TYPE,Globals::ACCOUNT_TYPE_CPS);

						$c->addAnd(TblAccountPeer::F_DIST_ID, $rs->getFId());

						$cps = TblAccountPeer::doSelectOne($c);

						

						if(sizeof($apos[$rs->getFLeg2()])) {

							//$aext[]=$rs;

							$aext[]['f_id']=$rs->getFId();

							$aext[]['f_code']=$rs->getFCode();

							$aext[]['f_nickname']=$rs->getFNickname();

							$aext[]['f_active_datetime']=$rs->getFActiveDatetime();

							$aext[]['f_leg2']=$rs->getFLeg2();

							$aext[]['f_cps']="CPS: ".$cps->getFBalance();

						} else {

							//$apos[$rs->getFLeg2()]=$rs;

							$apos[$rs->getFLeg2()]['f_id']=$rs->getFId();

							$apos[$rs->getFLeg2()]['f_code']=$rs->getFCode();

							$apos[$rs->getFLeg2()]['f_nickname']=$rs->getFNickname();

							$apos[$rs->getFLeg2()]['f_active_datetime']=$rs->getFActiveDatetime();

							$apos[$rs->getFLeg2()]['f_leg2']=$rs->getFLeg2();

							$apos[$rs->getFLeg2()]['f_cps']="CPS: ".$cps->getFBalance();

						}

					}

					if(sizeof($aext))

					foreach($aext as $key=>$value) {

						foreach($apos as $pkey=>$pvalue) {

							if(!sizeof($pvalue)) {

								$apos[$pkey]=$value;

								break;

							}

						}

					}

					foreach($apos as $key=>$value) {

						$id = $anode[6]["f_id"];

						$c = new Criteria();

						$c->add(TblDistributorPeer::F_PARENTID2, $id);

						$placements = TblDistributorPeer::doSelect($c);

						

						$left_cf = 0;

						$right_cf = 0;

						$left_mcf = 0;

						$right_mcf = 0;

						$cf_amount = 0;

						foreach($placements as $placement){

							$c = new Criteria();

							$c->add(TblPointCfPeer::F_DIST_ID, $placement->getFId());

							$c->addDescendingOrderByColumn(TblPointCfPeer::F_DATE);

							$cf = TblPointCfPeer::doSelectOne($c);

							if($cf) $cf_amount = $cf->getFCf();

							

							$query = "SELECT SUM(f_gs) AS f_gs FROM tbl_point_cf WHERE f_date between '".date('Y-m')."-01' AND '".date('Y-m')."-31' AND f_dist_id=".$placement->getFId()." GROUP BY f_dist_id"; 

							$connection = Propel::getConnection();

							$statement = $connection->prepareStatement($query);

			    			$rs = $statement->executeQuery();

			    						    											

							if($placement->getFLeg2()==1){

								$left_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $left_mcf= $arr["f_gs"];

						        }

							}

							if($placement->getFLeg2()==2){

								$right_cf = $cf_amount;

								

								if ($rs->next()) {

						            $arr = $rs->getRow();

						            $right_mcf= $arr["f_gs"];

						        }

							}

						}

						

						$anode[6]["f_pv"]="Carry Forward CPS: ".number_format($left_cf,0)." | ".number_format($right_cf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair where f_distributor_id=".$anode[6]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[6]["f_pv"].=$rs->fields["f_pv"];

							else $anode[6]["f_pv"].="0";

						} else $anode[6]["f_pv"].="0";*/

						$anode[6]["f_pv2"]="This Month CPS: ".number_format($left_mcf,0)." | ".number_format($right_mcf,0);

						/*if(isset($value["f_id"])) {

							$rs=mod::query("select f_bf+f_daily f_pv from bd_pair2 where f_distributor_id=".$anode[6]["f_id"]." and f_pass_up_by=".$value["f_id"]." order by f_date desc limit 1",$cnn);

							if(!$rs->EOF) $anode[6]["f_pv2"].=$rs->fields["f_pv"];

							else $anode[6]["f_pv2"].="0";

						} else $anode[6]["f_pv2"].="0";*/

					}

				}



				break;

			}

		}



		foreach($anode as $key=>$value) {

			if(!sizeof($value)) $anode[$key]["text"]="Available";

			else {

				$anode[$key]["text"]=$value["f_nickname"]."<br>"."<input value='".$value["f_code"]."' type='button' onclick=\"document.location.href='/member/placementTree?distcode=".$value["f_code"]."'\" /><br>".$value["f_active_datetime"]."<br>".$value["f_cps"]."<br>".$value["f_pv"]."<br>".$value["f_pv2"]."<br>";

			}

		}

		$this->anode=$anode;

    }

    

    public function executeGap()

    {

    	$this->title = "Genealogy";

    	$this->title2 = "Global Auto Placement";

    }

    

    public function executePlacePlacement()

    {

    	$this->title = "Business";

    	$this->title2 = "Place New Shareholder";

    	

    	$c = new Criteria();

    	$c->add(TblDistributorPeer::F_PARENTID2, '0');

    	$c->addAnd(TblDistributorPeer::F_PARENTID, $this->getUser()->getAttribute(Globals::SESSION_DISTID));

    	$c->addAnd(TblDistributorPeer::F_STATUS, Globals::STATUS_ACTIVE);

    	$this->TblDist = TblDistributorPeer::doSelect($c);

    }

    

    public function executeDoPlacement(){

    	$dist_id = $this->getRequestParameter('distid');

    	$leg = $this->getRequestParameter('position');

    	

    	if($leg==1)

    		$pos = "left";

    	elseif($leg==2)

    		$pos = "right";

    	

    	$id = $this->getUser()->getAttribute(Globals::SESSION_DISTID);

    	$placement = TblDistributorPeer::retrieveByPk($id);

    	

    	$tbl_dist = TblDistributorPeer::retrieveByPk($dist_id);

    	if($tbl_dist->getFParentid2()=='0' && $tbl_dist->getFParentid()==$this->getUser()->getAttribute(Globals::SESSION_DISTID) && ($leg=='1' || $leg=='2')){

    		

    		while($placement){

	    		$plamend_id = $placement->getFId();

	    		$plamend_code = $placement->getFCode();

	    		$c = new Criteria();

	    		$c->add(TblDistributorPeer::F_PARENTID2, $placement->getFId());

	    		$c->addAnd(TblDistributorPeer::F_LEG2, $leg);

	    		$placement = TblDistributorPeer::doSelectOne($c);

    		}

    		

    		$datetime = date("Y/m/d h:i:s A");

    		$tbl_dist->setFParentid2($plamend_id);

    		$tbl_dist->setFLeg2($leg);

    		$tbl_dist->setFPlacementDatetime($datetime);

    		$tbl_dist->save();

    		

    		$TblPlacement = new TblPlacement();

    		$TblPlacement->setFDistId($id);

    		$TblPlacement->setFDistId2($dist_id);

    		$TblPlacement->setFDistCode2($tbl_dist->getFCode());

    		$TblPlacement->setFParentid2($plamend_id);

    		$TblPlacement->setFParentidCode2($plamend_code);

    		$TblPlacement->setFLeg2($leg);

    		$TblPlacement->setFPosition($pos);

    		$TblPlacement->setFCreatedDatetime($datetime);

			$TblPlacement->save();

    	}

    	return $this->redirect('/member/placePlacement');

    }

    

    public function executeDailyBonus(){

    	$c = new Criteria();

        $c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_DAILY_BONUS);

        $exist = TblSettingPeer::doSelectOne($c);

               

        if($exist){

        	$c = new Criteria();

			$c->add(TblDistributorPeer::F_LEFT2, '0');

			$c->addAnd(TblDistributorPeer::F_PARENTID2, '0', Criteria::GREATER_THAN);

			$c->addAnd(TblDistributorPeer::F_STATUS, Globals::STATUS_ACTIVE);

			$rebuild_placement = TblDistributorPeer::doSelect($c);

			

			if($rebuild_placement){

				$this->rebuildplacement();

			}

        	

        	$c = new Criteria();

	        $c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_CPS);

	        $cps_rs = TblSettingPeer::doSelectOne($c);

			

	        if ($cps_rs) {

	            $cps = $cps_rs->getFValue();

	        }else{

	        	exit;

	        }

        	

        	for($number=date('j');$number<=date('j');$number++){ 

        	$date = split("-",$exist->getFValue());
        	
        	//$bonus_date = date('Y-m-d', mktime(0,0,0,$date[1],$date[2],$date[0]));
        	//$cf_date = date('Y-m-d', mktime(0,0,0,date("m"),date("d")-2,date("Y")));
        	//$today = date('Y-m-d');
        	//$bdate = date('d');
			//$bmonth = date('m');
			//$byear = date('Y');

			//$bdate = str_pad($number, 2, "0", STR_PAD_LEFT);
			$bdate = $date[2];
			//$bmonth = '1';
			$bmonth = $date[1];
			//$byear = '2012';
			$byear = $date[0];
			
        	$cf_date = date('Y-m-d', mktime(0,0,0,$bmonth,$bdate-1,$byear)); 
        	$bonus_date = date('Y-m-d', mktime(0,0,0,$bmonth,$bdate,$byear)); 
        	$today = date('Y-m-d', mktime(0,0,0,$bmonth,$bdate+1,$byear));

        	$query = "SELECT a.f_code, a.f_id, a.f_parentid, a.f_parentid2, a.f_leg2, CASE WHEN b.f_cf IS NULL THEN 0 ELSE b.f_cf END AS f_cf, c.f_balance FROM tbl_distributor a INNER JOIN tbl_account c ON c.f_dist_id=a.f_id AND c.f_type='gold dividend' LEFT JOIN tbl_point_cf b ON b.f_dist_id=a.f_id AND b.f_date='".$cf_date."' WHERE a.f_status='active' AND date_format(a.f_active_datetime, '%Y-%m-%d')<='".$bonus_date."'";

			$connection = Propel::getConnection();

		    $statement = $connection->prepareStatement($query);

		    $r1 = $statement->executeQuery();

		    

        	while($r1->next()){

        		$f_id = $r1->getString('f_id');

        		

        		$distributor[$f_id]['left']['id']=0;

				$distributor[$f_id]['left']['bv']=0;

				$distributor[$f_id]['right']['id']=0;

				$distributor[$f_id]['right']['bv']=0;

				$distributor[$f_id]['bv']=0;

				$distributor[$f_id]['sponsor']=$r1->getString('f_parentid');

				$distributor[$f_id]['placement']=$r1->getString('f_parentid2');

				$distributor[$f_id]['position']=$r1->getString('f_leg2');

				$distributor[$f_id]['dsb']=0;

				$distributor[$f_id]['gdb']=0;

				$distributor[$f_id]['gap']=0;

				$distributor[$f_id]['elb']=0;

				$distributor[$f_id]['cf']=$r1->getString('f_cf');

				$distributor[$f_id]['ps']=0;

				$distributor[$f_id]['pgs1']=0;

				$distributor[$f_id]['pgs2']=0;

				

				if($r1->getString('f_balance')>=5 && $r1->getString('f_balance')<10){

					$distributor[$f_id]['percentage'] = 8;

				}elseif($r1->getString('f_balance')>=10 && $r1->getString('f_balance')<20){

					$distributor[$f_id]['percentage'] = 10;

				}elseif($r1->getString('f_balance')>=20 && $r1->getString('f_balance')<30){

					$distributor[$f_id]['percentage'] = 11;

				}elseif($r1->getString('f_balance')>=30 && $r1->getString('f_balance')<50){

					$distributor[$f_id]['percentage'] = 12;

				}elseif($r1->getString('f_balance')>=50 && $r1->getString('f_balance')<100){

					$distributor[$f_id]['percentage'] = 13;

				}elseif($r1->getString('f_balance')>=100){

					$distributor[$f_id]['percentage'] = 15;

				}else{

					$distributor[$f_id]['percentage'] = 0;

				}

								

        		if($r1->getString('f_leg2')==1){

					$distributor[$r1->getString('f_parentid2')]['left']['id']=$f_id;

					//$distributor[$r1->getString('f_parentid2')]['left']['bv']=$r1->getString('f_cf');

					$distributor[$r1->getString('f_parentid2')]['left']['bv']=0;

        		}

				if($r1->getString('f_leg2')==2){

					$distributor[$r1->getString('f_parentid2')]['right']['id']=$f_id;

					//$distributor[$r1->getString('f_parentid2')]['right']['bv']=$r1->getString('f_cf');

					$distributor[$r1->getString('f_parentid2')]['right']['bv']=0;

				}

        	}

        	

        	//if($bonus_date==date('Y-m-d', mktime(0,0,0,date("m"),date("d")-1,date("Y")))){

        	if(1==1){

        		$bonus_log = new TblBonusLog();

				$bonus_log->setFBonusType(Globals::ACCOUNT_LEDGER_ACTION_DAILY_BONUS);

				$bonus_log->setFBonusDate($bonus_date);

				$bonus_log->setFStartedDatetime(date('Y-m-d H:i:s'));

        		$bonus_log->save();

        		

        		//$query = "SELECT b.f_id, sum(a.f_unit) as f_unit FROM tbl_pin a INNER JOIN tbl_distributor b ON b.f_id=a.f_dist_id2 WHERE a.f_action IN ('register','reinvest') AND date_format(a.f_action_datetime, '%Y-%m-%d')<='".$bonus_date."' GROUP BY a.f_dist_id2";

        		$query = "SELECT b.f_id, sum(a.f_unit) as f_unit FROM tbl_pin a INNER JOIN tbl_distributor b ON b.f_id=a.f_dist_id2 WHERE a.f_action IN ('register','reinvest') AND date_format(a.f_action_datetime, '%Y-%m-%d')='".$bonus_date."' GROUP BY a.f_dist_id2";

				$connection = Propel::getConnection();

		        $statement = $connection->prepareStatement($query);

		        $r2 = $statement->executeQuery();

				

				while($r2->next()){

			    	if ($r2->getString('f_unit')>0) {

			        	$distributor[$r2->getString('f_id')]['ps']+=$r2->getString('f_unit');

			        	$distributor[$r2->getString('f_id')]['pgs1']+=$r2->getString('f_unit');

						$distributor[$r2->getString('f_id')]['pgs2']+=$r2->getString('f_unit');

						$percent = $distributor[$r2->getString('f_id')]['percentage'];

						

						$sponsor_amount = ($r2->getString('f_unit')*$cps)*($percent/100);

						$sponsor=$distributor[$r2->getString('f_id')]['sponsor'];

						$distributor[$sponsor]['dsb']+=$sponsor_amount;

						$comm = new TblMemberComm();

	                    $comm->setFDistId($sponsor);

	                    $comm->setFFromDistId($r2->getString('f_id'));

	                    $comm->setFType('dsb');

	                    $comm->setFVolumeType($cps);

	                    $comm->setFCps($r2->getString('f_unit'));

	                    $comm->setFAmount($r2->getString('f_unit')*0.1);

	                    $comm->setFAmount2($sponsor_amount);

	                    $comm->setFPercent($percent);

	                    $comm->setFBonusDate($bonus_date);

	                    $comm->setFDatetime(date('Y-m-d H:i:s'));

	                    $comm->save();

	                    

						while($sponsor>0){

							$distributor[$sponsor]['pgs1']+=$r2->getString('f_unit');

							$sponsor=$distributor[$sponsor]['sponsor'];

							if($sponsor==20) break;

						}

						

						$placement=$distributor[$r2->getString('f_id')]['placement'];

						while($placement>0){

							$distributor[$placement]['pgs2']+=$r2->getString('f_unit');

							$placement=$distributor[$placement]['placement'];

							if($placement==20) break;

						}

			        }

				}

				

				foreach ($distributor as $id=>$value){					

					$point = new TblPointCf();

					$point->setFDistId($id);

					$point->setFCf(($value['cf']+$value['pgs2'])+0);

	                $point->setFGs($value['pgs2']+0);

	                $point->setFPs($distributor[$id]['ps']+0);

	                $point->setFDate($bonus_date);

	                $point->save();

	                $pair_amount = 0;

					

					if($distributor[$id]['position']==1){

						$distributor[$distributor[$id]['placement']]['left']['bv']=($value['cf']+$value['pgs2'])+0;

						$distributor[$distributor[$id]['placement']]['left1']['bv']=($value['cf']+$value['pgs2'])+0;

					}

					if($distributor[$id]['position']==2){

						$distributor[$distributor[$id]['placement']]['right']['bv']=($value['cf']+$value['pgs2'])+0;

						$distributor[$distributor[$id]['placement']]['right2']['bv']=($value['cf']+$value['pgs2'])+0;

					}

						

					if($distributor[$distributor[$id]['placement']]['left']['bv']>=2500 && $distributor[$distributor[$id]['placement']]['right']['bv']>=2500){

						$comm = new TblMemberComm();

	                    $comm->setFDistId($distributor[$id]['placement']);

	                    if($distributor[$distributor[$id]['placement']]['left']['bv']>=$distributor[$distributor[$id]['placement']]['right']['bv']){

	                    	$comm->setFFromDistId($distributor[$distributor[$id]['placement']]['right']['id']);

	                    	$pair_unit = floor($distributor[$distributor[$id]['placement']]['right']['bv']/2500);

	                    	$pair_leg = 'right';

	                    }else{

	                    	$comm->setFFromDistId($distributor[$distributor[$id]['placement']]['left']['id']);

	                    	$pair_unit = floor($distributor[$distributor[$id]['placement']]['left']['bv']/2500);

	                    	$pair_leg = 'left';

	                    }

	                    $pair = $pair_unit * 2500;

	                    $pair_amount += $pair;

	                    $total_pair = 0;

	                    $c=new Criteria();

				        $c->addSelectColumn('SUM(f_paired_unit) as total_pair');

				        $c->addSelectColumn(TblMemberCommPeer::F_PAIRED_UNIT);

				 		$c->addGroupByColumn('f_dist_id');

				        $crit=$c->getNewCriterion(TblMemberCommPeer::F_DIST_ID,'1');

				        $c->addHaving($crit);

				        $pairing=TblMemberCommPeer::doSelectRS($c);

				        while ($pairing->next()){

				        	$total_pair = $pairing->getString(1);

				        	break;

				        }

	                    

	                    $percent = $distributor[$id]['percentage'];

	                    $flush_point = 0;

	                    if($pair>(25000/$cps) && $percent==8){

	                    	$flush_point = $pair - (25000/$cps);

	                    	$pair = (25000/$cps);

	                    }elseif($pair>(40000/$cps) && $percent==10){

	                    	$flush_point = $pair - (40000/$cps);

	                    	$pair = (40000/$cps);

	                    }elseif($pair>(72700/$cps) && $percent==11){

	                    	$flush_point = $pair - (72700/$cps);

	                    	$pair = (72700/$cps);

	                    }elseif($pair>(100000/$cps) && $percent==12){

	                    	$flush_point = $pair - (100000/$cps);

	                    	$pair = (100000/$cps);

	                    }elseif($pair>(153800/$cps) && $percent==13){

	                    	$flush_point = $pair - (153800/$cps);

	                    	$pair = (153800/$cps);

	                    }elseif($pair>(266600/$cps) && $percent==15){

	                    	$flush_point = $pair - (266600/$cps);

	                    	$pair = (266600/$cps);

	                    }elseif($percent<=0){

	                    	$flush_point = $pair;

	                    	$pair = 0;

	                    }

	                    

	                    if($pair>0){

	                    	$pair_amount = ($pair*$cps)*($percent/100);

			                $comm->setFType('gdb');

			                $comm->setFVolumeType($cps);

			                $comm->setFAmount($pair*($percent/100));

			                $comm->setFAmount2($pair_amount);

			                $comm->setFPercent($percent);

			                $comm->setFLeg1Id($distributor[$distributor[$id]['placement']]['left']['id']);

			                $comm->setFLeg1Amount($distributor[$distributor[$id]['placement']]['left']['bv']);

			                $comm->setFLeg2Id($distributor[$distributor[$id]['placement']]['right']['id']);

			                $comm->setFLeg2Amount($distributor[$distributor[$id]['placement']]['right']['bv']);

			                $comm->setFPairedUnit($pair);

			                $comm->setFBonusDate($bonus_date);

			                $comm->setFDatetime(date('Y-m-d H:i:s'));

			                $comm->save();

							$distributor[$distributor[$id]['placement']]['gdb']+=$pair_amount;

							$c = new Criteria();
		                    $c->add(TblPointCfPeer::F_DIST_ID, $distributor[$distributor[$id]['placement']]['left']['id']);
		                    $c->addAnd(TblPointCfPeer::F_DATE, $bonus_date);
		                    $cf = TblPointCfPeer::doSelectOne($c);
		                    if($cf){
		                    	$cf_point = $distributor[$distributor[$id]['placement']]['left']['bv'] - $pair;
		                    	$cf->setFCf($cf_point);
		                    	$cf->save();
		                    }
		                    
		                    $c = new Criteria();
		                    $c->add(TblPointCfPeer::F_DIST_ID, $distributor[$distributor[$id]['placement']]['right']['id']);
		                    $c->addAnd(TblPointCfPeer::F_DATE, $bonus_date);
		                    $cf = TblPointCfPeer::doSelectOne($c);
		                    if($cf){
		                    	$cf_point = $distributor[$distributor[$id]['placement']]['right']['bv'] - $pair;
		                    	$cf->setFCf($cf_point);
		                    	$cf->save();
		                    }
	                    }

	                    if($flush_point>0){
	                    	$c = new Criteria();
			                $c->add(TblPointCfPeer::F_DIST_ID, $distributor[$distributor[$id]['placement']]['left']['id']);
			                $c->addAnd(TblPointCfPeer::F_DATE, $bonus_date);
			                $cf = TblPointCfPeer::doSelectOne($c);
							
							$cf_point = $distributor[$distributor[$id]['placement']]['left']['bv'] - $flush_point;
							
			                if($cf){
			                    $cf->setFFlush($flush_point);
			                    $cf->setFCf($cf_point);
			                    $cf->save();
			                }else{
			                	$cf = new TblPointCf();
			                	$cf->setFDistId($distributor[$distributor[$id]['placement']]['left']['id']);
			                	$cf->setFDate($bonus_date);
			                	$cf->setFFlush($flush_point);
			                    $cf->setFCf($cf_point);
			                    $cf->save();
			                }

	                    	$c = new Criteria();
			                $c->add(TblPointCfPeer::F_DIST_ID, $distributor[$distributor[$id]['placement']]['right']['id']);
			                $c->addAnd(TblPointCfPeer::F_DATE, $bonus_date);
			                $cf = TblPointCfPeer::doSelectOne($c);
							
							$cf_point = $distributor[$distributor[$id]['placement']]['right']['bv'] - $flush_point;
							
			                if($cf){
			                    $cf->setFFlush($flush_point);
			                    $cf->setFCf($cf_point);
			                    $cf->save();
			                }else{
			                	$cf = new TblPointCf();
			                	$cf->setFDistId($distributor[$distributor[$id]['placement']]['right']['id']);
			                	$cf->setFDate($bonus_date);
			                	$cf->setFFlush($flush_point);
			                    $cf->setFCf($cf_point);
			                    $cf->save();
			                }
	                    }

	                    $distributor[$distributor[$id]['placement']]['bv'] = $pair;

					}

				}

				

				foreach ($distributor as $distid=>$value) {

					if(date('N')=='1' || $bonus_date=='2012-02-06'){
		            	if($distributor[$distid]['left']['bv']>25000){
		                   	$c = new Criteria();
				            $c->add(TblPointCfPeer::F_DIST_ID, $distributor[$distid]['left']['id']);
				            $c->addAnd(TblPointCfPeer::F_DATE, $bonus_date);
				            $cf = TblPointCfPeer::doSelectOne($c);
	
							$flush_point = 0;
								
				            if($cf){
				                $flush_point = $cf->getFFlush() + ($distributor[$distid]['left']['bv'] - 25000);
	
				                $cf->setFFlush($flush_point);
				                $cf->setFCf(25000);
				                $cf->save();
	
			                }else{
			                	$flush_point = $distributor[$distid]['left']['bv'] - 25000;
				                	
			                	$cf = new TblPointCf();
			                	$cf->setFDistId($distributor[$distid]['left']['id']);
			                	$cf->setFDate($bonus_date);
			                    $cf->setFFlush($flush_point);
			                    $cf->setFCf(25000);
			                    $cf->save();			                	
			                }
			                
			                $distributor[$distid]['left']['bv'] = 25000;
		                }
		                    
		                if($distributor[$distid]['right']['bv']>25000){
		                  	$c = new Criteria();
			                $c->add(TblPointCfPeer::F_DIST_ID, $distributor[$distid]['right']['id']);
			                $c->addAnd(TblPointCfPeer::F_DATE, $bonus_date);
			                $cf = TblPointCfPeer::doSelectOne($c);
	
							$flush_point = 0;
							
			                if($cf){
			                    $flush_point = $cf->getFFlush() + ($distributor[$distid]['right']['bv'] - 25000);
	
			                    $cf->setFFlush($flush_point);
			                    $cf->setFCf(25000);
			                    $cf->save();
	
			                }else{
			                	$flush_point = $distributor[$distid]['right']['bv'] - 25000;
				                	
			                	$cf = new TblPointCf();
			                	$cf->setFDistId($distributor[$distid]['right']['id']);
			                	$cf->setFDate($bonus_date);
			                    $cf->setFFlush($flush_point);
			                    $cf->setFCf(25000);
			                    $cf->save();			                	
			                }
			                
			                $distributor[$distid]['right']['bv'] = 25000;
	                    }
					}
					
					$point_calc = new TblPointCalc();

					$point_calc->setFDistId($distid);

					$point_calc->setFLeftLeg($distributor[$distid]['left']['id']+0);

					$point_calc->setFLeftCf($distributor[$distid]['left']['bv']+0);

	                $point_calc->setFRightLeg($distributor[$distid]['right']['id']+0);

	                $point_calc->setFRightCf($distributor[$distid]['right']['bv']+0);

	                $point_calc->setFPairedAmount($distributor[$distid]['bv']+0);

	                $point_calc->setFDate($bonus_date);

	                $point_calc->save();

					

					$ttl_amount = $value['dsb']+$value['gdb']+$value['gap']+0;

					

					$bonus = new TblMemberCommSum();

					$bonus->setFDistId($distid);

					$bonus->setFDsb($value['dsb']+0);

					$bonus->setFGdb($value['gdb']+0);

					$bonus->setFGap($value['gap']+0);

					$bonus->setFBonusDate($bonus_date);

					$bonus->setFDatetime(date('Y-m-d H:i:s'));

					$bonus->save();

					

					if($ttl_amount>0){

						$c = new Criteria();

						$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

						$c->addAnd(TblAccountPeer::F_DIST_ID, $distid);

						$ecash = TblAccountPeer::doSelectOne($c);

				        

				        if(!$ecash){

				        	$ecash = new TblAccount();

				        	$ecash->setFType(Globals::ACCOUNT_TYPE_ECASH);

				        	$ecash->setFDistId($distid);

				        	$ecash->setFBalance('0.00');

				        	$ecash->save();

				        }

				        

				        $tbl_account_ledger = new TblAccountLedger();

				        $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_ECASH);

				        $tbl_account_ledger->setFDistId($distid);

				        $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_DAILY_BONUS." ".$bonus_date);

				        $tbl_account_ledger->setFCredit($ttl_amount);

				        $tbl_account_ledger->setFDebit(0);

				        $tbl_account_ledger->setFBalance($ecash->getFBalance()+$ttl_amount);

				        $tbl_account_ledger->setFCreatedDatetime(date('Y-m-d H:i:s'));

				        $tbl_account_ledger->save();

					    $this->revalidateAccount($distid, Globals::ACCOUNT_TYPE_ECASH);

					}

					    

				}

				

				//gold dividend

				$c = new Criteria();

				$c->add(TblAccountLedgerPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD_DIVIDEND);

				$c->addAnd(TblAccountLedgerPeer::F_CREDIT, '0', Criteria::GREATER_THAN);

				$c->addAnd(TblAccountLedgerPeer::F_CREATED_DATETIME, date("Y-m-d", mktime(0, 0, 0, $bmonth, $bdate-30, $byear)).'%', Criteria::LIKE);

				$gold_dividend_rs = TblAccountLedgerPeer::doSelect($c);

				foreach($gold_dividend_rs as $gd){

					$c = new Criteria();

					$c->add(TblAccountPeer::F_DIST_ID, $gd->getFDistId());

					$c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD);

					$gold_bal = TblAccountPeer::doSelectOne($c);

					

					$gold = new TblAccountLedger();

					$gold->setFDistId($gd->getFDistId());

					$gold->setFType(Globals::ACCOUNT_TYPE_GOLD);

					$gold->setFAction(Globals::ACCOUNT_LEDGER_ACTION_WITHDRAWAL);

					$gold->setFCredit($gd->getFCredit());

					$gold->setFBalance($gold_bal->getFBalance()+$gd->getFCredit());

					$gold->setFCreatedDatetime($bonus_date.date(' H:i:s'));

					$gold->save();

					

					$gold_bal->setFBalance($gold_bal->getFBalance()+$gd->getFCredit());

					$gold_bal->save();

					

					$gd->setFCreatedDatetime($bonus_date." 00:00:00");

					$gd->save();

				}				

				

				$bonus_log->setFCompletedDatetime(date('Y-m-d H:i:s'));

				$bonus_log->save();

				

				$query = "UPDATE tbl_pin a INNER JOIN tbl_distributor b ON b.f_id=a.f_dist_id2 SET a.f_is_calc=1 WHERE a.f_action IN ('register','reinvest') AND date_format(a.f_action_datetime, '%Y-%m-%d')='".$bonus_date."'";

				$connection = Propel::getConnection();

		        $statement = $connection->prepareStatement($query);

		        $statement->executeQuery();

								

				$exist->setFValue($today);

				$exist->save();

				print_r('Finish');

				//exit;					

        	}else{

        		print_r('Daily bonus');

        		//exit;

        	}

        	}

        }
        exit;
    }

    /*public function executeDailyBonus(){

    	$c = new Criteria();

        $c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_DAILY_BONUS);

        $exist = TblSettingPeer::doSelectOne($c);

               

        if($exist){

        	$c = new Criteria();

	        $c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_CPS);

	        $cps_rs = TblSettingPeer::doSelectOne($c);

			

	        if ($cps_rs) {

	            $cps = $cps_rs->getFValue();

	            $cps = '0.90';

	        }else{

	        	exit;

	        }

        	

        	for($number=10;$number<=31;$number++){ 

        	$date = split("-",$exist->getFValue());

        	$bonus_date = date('Y-m-d', mktime(0,0,0,$date[1],$date[2],$date[0]));

        	$cf_date = date('Y-m-d', mktime(0,0,0,date("m"),date("d")-2,date("Y")));

        	$today = date('Y-m-d');

        	//$bdate = date('d');

			//$bmonth = date('m');

			//$byear = date('Y');

			$bdate = str_pad($number, 2, "0", STR_PAD_LEFT);

			$bmonth = '11';

			$byear = '2011';

        	$cf_date = '2011-11-'.str_pad($number-1, 2, "0", STR_PAD_LEFT); $bonus_date = '2011-11-'.str_pad($number, 2, "0", STR_PAD_LEFT); $today = '2011-11-'.str_pad($number+1, 2, "0", STR_PAD_LEFT);

        	$query = "SELECT a.f_code, a.f_id, a.f_parentid, a.f_parentid2, a.f_leg2, CASE WHEN b.f_cf IS NULL THEN 0 ELSE b.f_cf END AS f_cf FROM tbl_distributor a LEFT JOIN tbl_point_cf b ON b.f_dist_id=a.f_id AND b.f_date='".$cf_date."' WHERE a.f_status='active' AND date_format(a.f_active_datetime, '%Y-%m-%d')<='".$bonus_date."'";

			$connection = Propel::getConnection();

		    $statement = $connection->prepareStatement($query);

		    $r1 = $statement->executeQuery();

		    

        	while($r1->next()){

        		$f_id = $r1->getString('f_id');

        		

        		$distributor[$f_id]['left']['id']=0;

				$distributor[$f_id]['left']['bv']=0;

				$distributor[$f_id]['right']['id']=0;

				$distributor[$f_id]['right']['bv']=0;

				$distributor[$f_id]['bv']=0;

				$distributor[$f_id]['sponsor']=$r1->getString('f_parentid');

				$distributor[$f_id]['placement']=$r1->getString('f_parentid2');

				$distributor[$f_id]['position']=$r1->getString('f_leg2');

				$distributor[$f_id]['dsb']=0;

				$distributor[$f_id]['gdb']=0;

				$distributor[$f_id]['gap']=0;

				$distributor[$f_id]['elb']=0;

				$distributor[$f_id]['cf']=$r1->getString('f_cf');

				$distributor[$f_id]['ps']=0;

				$distributor[$f_id]['pgs1']=0;

				$distributor[$f_id]['pgs2']=0;

								

        		if($r1->getString('f_leg2')==1){

					$distributor[$r1->getString('f_parentid2')]['left']['id']=$f_id;

					//$distributor[$r1->getString('f_parentid2')]['left']['bv']=$r1->getString('f_cf');

					$distributor[$r1->getString('f_parentid2')]['left']['bv']=0;

        		}

				if($r1->getString('f_leg2')==2){

					$distributor[$r1->getString('f_parentid2')]['right']['id']=$f_id;

					//$distributor[$r1->getString('f_parentid2')]['right']['bv']=$r1->getString('f_cf');

					$distributor[$r1->getString('f_parentid2')]['right']['bv']=0;

				}

        	}

        	

        	//if($bonus_date==date('Y-m-d', mktime(0,0,0,date("m"),date("d")-1,date("Y")))){

        	if(1==1){

        		$bonus_log = new TblBonusLog();

				$bonus_log->setFBonusType(Globals::ACCOUNT_LEDGER_ACTION_DAILY_BONUS);

				$bonus_log->setFBonusDate($bonus_date);

				$bonus_log->setFStartedDatetime(date('Y-m-d H:i:s'));

        		$bonus_log->save();

        		

        		//$query = "SELECT b.f_id, sum(a.f_unit) as f_unit FROM tbl_pin a INNER JOIN tbl_distributor b ON b.f_id=a.f_dist_id2 WHERE a.f_action IN ('register','reinvest') AND date_format(a.f_action_datetime, '%Y-%m-%d')<='".$bonus_date."' GROUP BY a.f_dist_id2";

        		$query = "SELECT b.f_id, sum(a.f_unit) as f_unit FROM tbl_pin a INNER JOIN tbl_distributor b ON b.f_id=a.f_dist_id2 WHERE a.f_action IN ('register','reinvest') AND date_format(a.f_action_datetime, '%Y-%m-%d')='".$bonus_date."' GROUP BY a.f_dist_id2";

				$connection = Propel::getConnection();

		        $statement = $connection->prepareStatement($query);

		        $r2 = $statement->executeQuery();

				

				while($r2->next()){

			    	if ($r2->getString('f_unit')>0) {

			        	$distributor[$r2->getString('f_id')]['ps']+=$r2->getString('f_unit');

			        	$distributor[$r2->getString('f_id')]['pgs1']+=$r2->getString('f_unit');

						$distributor[$r2->getString('f_id')]['pgs2']+=$r2->getString('f_unit');

												

						$sponsor_amount = ($r2->getString('f_unit')*$cps)*0.1;

						$sponsor=$distributor[$r2->getString('f_id')]['sponsor'];

						$distributor[$sponsor]['dsb']+=$sponsor_amount;

						$comm = new TblMemberComm();

	                    $comm->setFDistId($sponsor);

	                    $comm->setFFromDistId($r2->getString('f_id'));

	                    $comm->setFType('dsb');

	                    $comm->setFVolumeType($cps);

	                    $comm->setFCps($r2->getString('f_unit'));

	                    $comm->setFAmount($r2->getString('f_unit')*0.1);

	                    $comm->setFAmount2($sponsor_amount);

	                    $comm->setFPercent('10');

	                    $comm->setFBonusDate($bonus_date);

	                    $comm->setFDatetime(date('Y-m-d H:i:s'));

	                    $comm->save();

	                    

						while($sponsor>0){

							$distributor[$sponsor]['pgs1']+=$r2->getString('f_unit');

							$sponsor=$distributor[$sponsor]['sponsor'];

							if($sponsor==20) break;

						}

						

						$placement=$distributor[$r2->getString('f_id')]['placement'];

						while($placement>0){

							$distributor[$placement]['pgs2']+=$r2->getString('f_unit');

							$placement=$distributor[$placement]['placement'];

							if($placement==20) break;

						}

			        }

				}

				

				foreach ($distributor as $id=>$value){					

					$point = new TblPointCf();

					$point->setFDistId($id);

					$point->setFCf(($value['cf']+$value['pgs2'])+0);

	                $point->setFGs($value['pgs2']+0);

	                $point->setFPs($distributor[$id]['ps']+0);

	                $point->setFDate($bonus_date);

	                $point->save();

	                $pair_amount = 0;

					

					if($distributor[$id]['position']==1){

						$distributor[$distributor[$id]['placement']]['left']['bv']=($value['cf']+$value['pgs2'])+0;

						$distributor[$distributor[$id]['placement']]['left1']['bv']=($value['cf']+$value['pgs2'])+0;

					}

					if($distributor[$id]['position']==2){

						$distributor[$distributor[$id]['placement']]['right']['bv']=($value['cf']+$value['pgs2'])+0;

						$distributor[$distributor[$id]['placement']]['right2']['bv']=($value['cf']+$value['pgs2'])+0;

					}

						

					if($distributor[$distributor[$id]['placement']]['left']['bv']>=2000 && $distributor[$distributor[$id]['placement']]['right']['bv']>=2000){

						$comm = new TblMemberComm();

	                    $comm->setFDistId($distributor[$id]['placement']);

	                    if($distributor[$distributor[$id]['placement']]['left']['bv']>=$distributor[$distributor[$id]['placement']]['right']['bv']){

	                    	$comm->setFFromDistId($distributor[$distributor[$id]['placement']]['right']['id']);

	                    	$pair_unit = floor($distributor[$distributor[$id]['placement']]['right']['bv']/2000);	                    	

	                    }else{

	                    	$comm->setFFromDistId($distributor[$distributor[$id]['placement']]['left']['id']);

	                    	$pair_unit = floor($distributor[$distributor[$id]['placement']]['left']['bv']/2000);

	                    }

	                    $pair = $pair_unit * 2000;

	                    $pair_amount += $pair;

	                    $total_pair = 0;

	                    $c=new Criteria();

				        $c->addSelectColumn('SUM(f_paired_unit) as total_pair');

				        $c->addSelectColumn(TblMemberCommPeer::F_PAIRED_UNIT);

				 		$c->addGroupByColumn('f_dist_id');

				        $crit=$c->getNewCriterion(TblMemberCommPeer::F_DIST_ID,'1');

				        $c->addHaving($crit);

				        $pairing=TblMemberCommPeer::doSelectRS($c);

				        while ($pairing->next()){

				        	$total_pair = $pairing->getString(1);

				        	break;

				        }

	                    

	                    if($total_pair>=0 && $total_pair<=50000){

	                    	$percent = 10;

	                    	$bal_pair = 50000-$total_pair;

	                    	if($pair>$bal_pair){

	                    		$pair_amount = ($bal_pair*$cps)/$percent;

			                    $comm->setFType('gdb');

			                    $comm->setFVolumeType($cps);

			                    $comm->setFAmount($bal_pair/$percent);

			                    $comm->setFAmount2($pair_amount);

			                    $comm->setFPercent($percent);

			                    $comm->setFLeg1Id($distributor[$distributor[$id]['placement']]['left']['id']+0);

			                    $comm->setFLeg1Amount($distributor[$distributor[$id]['placement']]['left']['bv']+0);

			                    $comm->setFLeg2Id($distributor[$distributor[$id]['placement']]['right']['id']+0);

			                    $comm->setFLeg2Amount($distributor[$distributor[$id]['placement']]['right']['bv']+0);

			                    $comm->setFPairedUnit($bal_pair);

			                    $comm->setFBonusDate($bonus_date);

			                    $comm->setFDatetime(date('Y-m-d H:i:s'));

			                    $comm->save();

								$distributor[$distributor[$id]['placement']]['gdb']+=$pair_amount;

								

								$pair2 = $pair-$bal_pair;

								if($pair2>50000){

									$percent = 5;

									$comm2 = new TblMemberComm();

	                    			$comm2->setFDistId($distributor[$id]['placement']);

	                    			$comm2->setFFromDistId($comm->getFFromDistId());

	                    			$pair_amount = (50000*$cps)/$percent;

				                    $comm2->setFType('gdb');

				                    $comm2->setFVolumeType($cps);

				                    $comm2->setFAmount(50000/$percent);

				                    $comm2->setFAmount2($pair_amount);

				                    $comm2->setFPercent($percent);

				                    $comm2->setFLeg1Id($distributor[$distributor[$id]['placement']]['left']['id']);

				                    $comm2->setFLeg1Amount($distributor[$distributor[$id]['placement']]['left']['bv']-$bal_pair);

				                    $comm2->setFLeg2Id($distributor[$distributor[$id]['placement']]['right']['id']);

				                    $comm2->setFLeg2Amount($distributor[$distributor[$id]['placement']]['right']['bv']-$bal_pair);

				                    $comm2->setFPairedUnit(50000);

				                    $comm2->setFBonusDate($bonus_date);

				                    $comm2->setFDatetime(date('Y-m-d H:i:s'));

				                    $comm2->save();

									$distributor[$distributor[$id]['placement']]['gdb']+=$pair_amount;

									

									$pair3 = $pair2-50000;

									$percent = 3;

									$comm3 = new TblMemberComm();

	                    			$comm3->setFDistId($distributor[$id]['placement']);

	                    			$comm3->setFFromDistId($comm->getFFromDistId());

	                    			$pair_amount = ($pair3*$cps)/$percent;

				                    $comm3->setFType('gdb');

				                    $comm3->setFVolumeType($cps);

				                    $comm3->setFAmount($pair3/$percent);

				                    $comm3->setFAmount2($pair_amount);

				                    $comm3->setFPercent($percent);

				                    $comm3->setFLeg1Id($distributor[$distributor[$id]['placement']]['left']['id']);

				                    $comm3->setFLeg1Amount($distributor[$distributor[$id]['placement']]['left']['bv']-($bal_pair+50000));

				                    $comm3->setFLeg2Id($distributor[$distributor[$id]['placement']]['right']['id']);

				                    $comm3->setFLeg2Amount($distributor[$distributor[$id]['placement']]['right']['bv']-($bal_pair+50000));

				                    $comm3->setFPairedUnit($pair3);

				                    $comm3->setFBonusDate($bonus_date);

				                    $comm3->setFDatetime(date('Y-m-d H:i:s'));

				                    $comm3->save();

									$distributor[$distributor[$id]['placement']]['gdb']+=$pair_amount;

								}else{

									$percent = 5;

									$comm2 = new TblMemberComm();

	                    			$comm2->setFDistId($distributor[$id]['placement']);

	                    			$comm2->setFFromDistId($comm->getFFromDistId());

	                    			$pair_amount = ($pair2*$cps)/$percent;

				                    $comm->setFType('gdb');

				                    $comm->setFVolumeType($cps);

				                    $comm->setFAmount($pair2/$percent);

				                    $comm->setFAmount2($pair_amount);

				                    $comm->setFPercent($percent);

				                    $comm->setFLeg1Id($distributor[$distributor[$id]['placement']]['left']['id']);

				                    $comm->setFLeg1Amount($distributor[$distributor[$id]['placement']]['left']['bv']-$bal_pair);

				                    $comm->setFLeg2Id($distributor[$distributor[$id]['placement']]['right']['id']);

				                    $comm->setFLeg2Amount($distributor[$distributor[$id]['placement']]['right']['bv']-$bal_pair);

				                    $comm->setFPairedUnit($pair2);

				                    $comm->setFBonusDate($bonus_date);

				                    $comm->setFDatetime(date('Y-m-d H:i:s'));

				                    $comm->save();

									$distributor[$distributor[$id]['placement']]['gdb']+=$pair_amount;

								}

	                    	}else{

	                    		$percent = 10;

	                    		$pair_amount = ($pair*$cps)/$percent;

			                    $comm->setFType('gdb');

			                    $comm->setFVolumeType($cps);

			                    $comm->setFAmount($pair/$percent);

			                    $comm->setFAmount2($pair_amount);

			                    $comm->setFPercent($percent);

			                    $comm->setFLeg1Id($distributor[$distributor[$id]['placement']]['left']['id']);

			                    $comm->setFLeg1Amount($distributor[$distributor[$id]['placement']]['left']['bv']);

			                    $comm->setFLeg2Id($distributor[$distributor[$id]['placement']]['right']['id']);

			                    $comm->setFLeg2Amount($distributor[$distributor[$id]['placement']]['right']['bv']);

			                    $comm->setFPairedUnit($pair);

			                    $comm->setFBonusDate($bonus_date);

			                    $comm->setFDatetime(date('Y-m-d H:i:s'));

			                    $comm->save();

								$distributor[$distributor[$id]['placement']]['gdb']+=$pair_amount;

								

	                    	}

	                    }elseif($total_pair>=50001 && $total_pair<=100000){

	                    	$percent = 5;

	                    	$bal_pair = 100000-$total_pair;

	                    	if($pair>$bal_pair){

	                    		$pair_amount = ($bal_pair*$cps)/$percent;

			                    $comm->setFType('gdb');

			                    $comm->setFVolumeType($cps);

			                    $comm->setFAmount($bal_pair/$percent);

			                    $comm->setFAmount2($pair_amount);

			                    $comm->setFPercent($percent);

			                    $comm->setFLeg1Id($distributor[$distributor[$id]['placement']]['left']['id']);

			                    $comm->setFLeg1Amount($distributor[$distributor[$id]['placement']]['left']['bv']);

			                    $comm->setFLeg2Id($distributor[$distributor[$id]['placement']]['right']['id']);

			                    $comm->setFLeg2Amount($distributor[$distributor[$id]['placement']]['right']['bv']);

			                    $comm->setFPairedUnit($bal_pair);

			                    $comm->setFBonusDate($bonus_date);

			                    $comm->setFDatetime(date('Y-m-d H:i:s'));

			                    $comm->save();

								$distributor[$distributor[$id]['placement']]['gdb']+=$pair_amount;

								

								$pair2 = $pair-$bal_pair;

								if($pair2>0){

									$percent = 3;

									$comm2 = new TblMemberComm();

	                    			$comm2->setFDistId($distributor[$id]['placement']);

	                    			$comm2->setFFromDistId($comm->getFFromDistId());

	                    			$pair_amount = ($pair2*$cps)/$percent;

				                    $comm->setFType('gdb');

				                    $comm->setFVolumeType($cps);

				                    $comm->setFAmount($pair2/$percent);

				                    $comm->setFAmount2($pair_amount);

				                    $comm->setFPercent($percent);

				                    $comm->setFLeg1Id($distributor[$distributor[$id]['placement']]['left']['id']);

				                    $comm->setFLeg1Amount($distributor[$distributor[$id]['placement']]['left']['bv']-$bal_pair);

				                    $comm->setFLeg2Id($distributor[$distributor[$id]['placement']]['right']['id']);

				                    $comm->setFLeg2Amount($distributor[$distributor[$id]['placement']]['right']['bv']-$bal_pair);

				                    $comm->setFPairedUnit($pair2);

				                    $comm->setFBonusDate($bonus_date);

				                    $comm->setFDatetime(date('Y-m-d H:i:s'));

				                    $comm->save();

									$distributor[$distributor[$id]['placement']]['gdb']+=$pair_amount;

								}

	                    	}else{

	                    		$percent = 5;

	                    		$pair_amount = ($pair*$cps)/$percent;

			                    $comm->setFType('gdb');

			                    $comm->setFVolumeType($cps);

			                    $comm->setFAmount($pair/$percent);

			                    $comm->setFAmount2($pair_amount);

			                    $comm->setFPercent($percent);

			                    $comm->setFLeg1Id($distributor[$distributor[$id]['placement']]['left']['id']);

			                    $comm->setFLeg1Amount($distributor[$distributor[$id]['placement']]['left']['bv']);

			                    $comm->setFLeg2Id($distributor[$distributor[$id]['placement']]['right']['id']);

			                    $comm->setFLeg2Amount($distributor[$distributor[$id]['placement']]['right']['bv']);

			                    $comm->setFPairedUnit($pair);

			                    $comm->setFBonusDate($bonus_date);

			                    $comm->setFDatetime(date('Y-m-d H:i:s'));

			                    $comm->save();

								$distributor[$distributor[$id]['placement']]['gdb']+=$pair_amount;

								

	                    	}

	                    }else{

	                    	$percent = 3;

	                    	$pair_amount = ($pair*$cps)/$percent;

			                $comm->setFType('gdb');

			                $comm->setFVolumeType($cps);

			                $comm->setFAmount($pair/$percent);

			                $comm->setFAmount2($pair_amount);

			                $comm->setFPercent($percent);

			                $comm->setFLeg1Id($distributor[$distributor[$id]['placement']]['left']['id']);

			                $comm->setFLeg1Amount($distributor[$distributor[$id]['placement']]['left']['bv']);

			                $comm->setFLeg2Id($distributor[$distributor[$id]['placement']]['right']['id']);

			                $comm->setFLeg2Amount($distributor[$distributor[$id]['placement']]['right']['bv']);

			                $comm->setFPairedUnit($pair);

			                $comm->setFBonusDate($bonus_date);

			                $comm->setFDatetime(date('Y-m-d H:i:s'));

			                $comm->save();

							$distributor[$distributor[$id]['placement']]['gdb']+=$pair_amount;

	                    }

	                    

	                    $c = new Criteria();

	                    $c->add(TblPointCfPeer::F_DIST_ID, $distributor[$distributor[$id]['placement']]['left']['id']);

	                    $c->addAnd(TblPointCfPeer::F_DATE, $bonus_date);

	                    $cf = TblPointCfPeer::doSelectOne($c);

	                    if($cf){

	                    	$cf_point = $distributor[$distributor[$id]['placement']]['left']['bv'] - $pair;

	                    	if($cf_point>10000 && date('d')=='01'){

	                    		$flush_point = $cf_point - 10000;

	                    		$cf_point = 10000;

	                    		$cf->setFFlush($flush_point);

	                    	}

	                    	$cf->setFCf($cf_point);

	                    	$cf->save();

	                    }

	                    

	                    $c = new Criteria();

	                    $c->add(TblPointCfPeer::F_DIST_ID, $distributor[$distributor[$id]['placement']]['right']['id']);

	                    $c->addAnd(TblPointCfPeer::F_DATE, $bonus_date);

	                    $cf = TblPointCfPeer::doSelectOne($c);

	                    if($cf){

	                    	$cf_point = $distributor[$distributor[$id]['placement']]['right']['bv'] - $pair;

	                    	if($cf_point>10000 && date('d')=='01'){

	                    		$flush_point = $cf_point - 10000;

	                    		$cf_point = 10000;

	                    		$cf->setFFlush($flush_point);

	                    	}

	                    	$cf->setFCf($cf_point);

	                    	$cf->save();

	                    }

	                    

	                    $distributor[$distributor[$id]['placement']]['bv'] = $pair;

					}

				}

				

				if($bonus_date>='2011-10-05'){

					//gap

					$sql = "UPDATE tbl_distributor INNER JOIN tbl_account gold ON gold.f_dist_id=tbl_distributor.f_id AND gold.f_type='gold dividend' AND gold.f_balance>=30 INNER JOIN tbl_account gap ON gap.f_dist_id=tbl_distributor.f_id AND gap.f_balance>0 SET tbl_distributor.f_gap=1, tbl_distributor.f_gap_datetime='".$bonus_date.date(' H:i:s')."' WHERE tbl_distributor.f_gap=0 AND tbl_distributor.f_gap_datetime='0000-00-00 00:00:00'";

					$connection = Propel::getConnection();

			        $statement = $connection->prepareStatement($sql);

			        $statement->executeQuery();

			        

			        $sql = "SELECT tbl_distributor.f_id FROM tbl_distributor INNER JOIN tbl_account ON tbl_account.f_dist_id=tbl_distributor.f_id AND tbl_account.f_type='gap' AND tbl_account.f_balance>0 WHERE tbl_distributor.f_gap='1' AND tbl_distributor.f_status='active' ORDER BY tbl_account.f_balance DESC, tbl_distributor.f_id";

			        $connection = Propel::getConnection();

			        $statement = $connection->prepareStatement($sql);

			        $resultset = $statement->executeQuery();

			        $parentid=0;

			        $i=0;

			        while ($resultset->next()) {

			            $arr = $resultset->getRow();

			            

				        $gap = new TblGap();

				        $gap->setFDistId($arr['f_id']);

				        $gap->setFParentId($parentid);

				        $gap->setFLevel($i);

				        $gap->setFDate($bonus_date);

				        $gap->setFGap($distributor[$arr['f_id']]['gdb']+0);

				        $gap->save();

			            

			            $parentid = $arr['f_id'];

			            $i++;

			        }

			        

			        $c = new Criteria();

			        $c->add(TblGapPeer::F_DATE, $bonus_date);

			        $c->addDescendingOrderByColumn(TblGapPeer::F_LEVEL);

			        $rs_gap = TblGapPeer::doSelect($c);

			        

			        foreach($rs_gap as $gap){

			        	for($i=1;$i<=15;$i++){

			        		$c = new Criteria();

			        		$c->add(TblGapPeer::F_DIST_ID, $gap->getFParentid());

			        		$c->addAnd(TblGapPeer::F_DATE, $bonus_date);

			        		$gap_upline = TblGapPeer::doSelectOne($c);

			        		

			        		if($gap_upline){

			        			$gap_amount = $gap->getFGap()*0.02;

			        			$comm = new TblMemberComm();

				                $comm->setFDistId($gap_upline->getFDistId());

				                $comm->setFFromDistId($gap->getFDistId());

				                $comm->setFType('gap');

				                $comm->setFLevel($i);

				                $comm->setFVolumeType($gap->getFGap());

				                $comm->setFAmount($gap_amount);

				                $comm->setFPercent('2');

				                $comm->setFBonusDate($bonus_date);

				                $comm->setFDatetime(date('Y-m-d H:i:s'));

				                $comm->save();

				                $distributor[$gap_upline->getFDistId()]['gap']+=$gap_amount;

			        		}else{

			        			break;

			        		}

			        	}			        	

			        }

				}

				

				foreach ($distributor as $distid=>$value) {

					$point_calc = new TblPointCalc();

					$point_calc->setFDistId($distid);

					$point_calc->setFLeftLeg($distributor[$distid]['left']['id']+0);

					$point_calc->setFLeftCf($distributor[$distid]['left']['bv']+0);

	                $point_calc->setFRightLeg($distributor[$distid]['right']['id']+0);

	                $point_calc->setFRightCf($distributor[$distid]['right']['bv']+0);

	                $point_calc->setFPairedAmount($distributor[$distid]['bv']+0);

	                $point_calc->setFDate($bonus_date);

	                $point_calc->save();

					

					if($value['gap']>0){

						$c = new Criteria();

				        $c->add(TblAccountPeer::F_DIST_ID, $distid);

				        $c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GAP);

				        $gap_bal = TblAccountPeer::doSelectOne($c);

				        if($gap_bal->getFBalance()<$value['gap']){

				        	$value['gap'] = $gap_bal->getFBalance();

				        }

				        

				        $tbl_account_ledger = new TblAccountLedger();

				        $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_GAP);

				        $tbl_account_ledger->setFDistId($distid);

				        $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_DAILY_BONUS." ".$bonus_date);

				        $tbl_account_ledger->setFCredit(0);

				        $tbl_account_ledger->setFDebit($value['gap']);

				        $tbl_account_ledger->setFBalance($gap_bal->getFBalance()-$value['gap']);

				        $tbl_account_ledger->setFCreatedDatetime(date('Y-m-d H:i:s'));

				        $tbl_account_ledger->save();

					    $this->revalidateAccount($distid, Globals::ACCOUNT_TYPE_GAP);

					}

					

					$ttl_amount = $value['dsb']+$value['gdb']+$value['gap']+0;

					

					$bonus = new TblMemberCommSum();

					$bonus->setFDistId($distid);

					$bonus->setFDsb($value['dsb']+0);

					$bonus->setFGdb($value['gdb']+0);

					$bonus->setFGap($value['gap']+0);

					$bonus->setFBonusDate($bonus_date);

					$bonus->setFDatetime(date('Y-m-d H:i:s'));

					$bonus->save();

					

					if($ttl_amount>0){

						$c = new Criteria();

						$c->add(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

						$c->addAnd(TblAccountPeer::F_DIST_ID, $distid);

						$ecash = TblAccountPeer::doSelectOne($c);

				        

				        if(!$ecash){

				        	$ecash = new TblAccount();

				        	$ecash->setFType(Globals::ACCOUNT_TYPE_ECASH);

				        	$ecash->setFDistId($distid);

				        	$ecash->setFBalance('0.00');

				        	$ecash->save();

				        }

				        

				        $tbl_account_ledger = new TblAccountLedger();

				        $tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_ECASH);

				        $tbl_account_ledger->setFDistId($distid);

				        $tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_DAILY_BONUS." ".$bonus_date);

				        $tbl_account_ledger->setFCredit($ttl_amount);

				        $tbl_account_ledger->setFDebit(0);

				        $tbl_account_ledger->setFBalance($ecash->getFBalance()+$ttl_amount);

				        $tbl_account_ledger->setFCreatedDatetime(date('Y-m-d H:i:s'));

				        $tbl_account_ledger->save();

					    $this->revalidateAccount($distid, Globals::ACCOUNT_TYPE_ECASH);

					}

					    

				}

				

				//gold dividend

				$c = new Criteria();

				$c->add(TblAccountLedgerPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD_DIVIDEND);

				$c->addAnd(TblAccountLedgerPeer::F_CREDIT, '0', Criteria::GREATER_THAN);

				$c->addAnd(TblAccountLedgerPeer::F_CREATED_DATETIME, date("Y-m-d", mktime(0, 0, 0, $bmonth, $bdate-30, $byear)).'%', Criteria::LIKE);

				$gold_dividend_rs = TblAccountLedgerPeer::doSelect($c);

				foreach($gold_dividend_rs as $gd){

					$c = new Criteria();

					$c->add(TblAccountPeer::F_DIST_ID, $gd->getFDistId());

					$c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_GOLD);

					$gold_bal = TblAccountPeer::doSelectOne($c);

					

					$gold = new TblAccountLedger();

					$gold->setFDistId($gd->getFDistId());

					$gold->setFType(Globals::ACCOUNT_TYPE_GOLD);

					$gold->setFAction(Globals::ACCOUNT_LEDGER_ACTION_WITHDRAWAL);

					$gold->setFCredit($gd->getFCredit());

					$gold->setFBalance($gold_bal->getFBalance()+$gd->getFCredit());

					$gold->setFCreatedDatetime($bonus_date.date(' H:i:s'));

					$gold->save();

					

					$gold_bal->setFBalance($gold_bal->getFBalance()+$gd->getFCredit());

					$gold_bal->save();

					

					$gd->setFCreatedDatetime($bonus_date." 00:00:00");

					$gd->save();

				}				

				

				$bonus_log->setFCompletedDatetime(date('Y-m-d H:i:s'));

				$bonus_log->save();

				

				$query = "UPDATE tbl_pin a INNER JOIN tbl_distributor b ON b.f_id=a.f_dist_id2 SET a.f_is_calc=1 WHERE a.f_action IN ('register','reinvest') AND date_format(a.f_action_datetime, '%Y-%m-%d')='".$bonus_date."'";

				$connection = Propel::getConnection();

		        $statement = $connection->prepareStatement($query);

		        $statement->executeQuery();

								

				$exist->setFValue($today);

				$exist->save();

				print_r('Finish');

				//exit;					

        	}else{

        		print_r('Daily bonus');

        		//exit;

        	}

        	}

        }exit;

    }*/

    

    public function executeRecalculateCF(){

    	$c = new Criteria();

    	$c->add(TblPointCalcPeer::F_DATE, '2011-09-30');

    	$points = TblPointCalcPeer::doSelect($c);

    	foreach($points as $point){

	    	$query = "UPDATE tbl_point_calc SET f_left_cf=f_left_cf+".($point->getFLeftCf()-$point->getFPairedAmount()).",f_right_cf=f_right_cf+".($point->getFRightCf()-$point->getFPairedAmount())." WHERE f_dist_id=".$point->getFDistId()." AND f_date>='2011-10-01'";

			$connection = Propel::getConnection();

			$statement = $connection->prepareStatement($query);

			$statement->executeQuery();

    	}

    	print_r('done');

    	exit;

    }

    

    public function executeRecalculateEcash(){

    	$c = new Criteria();

    	$tbl_distributor = TblDistributorPeer::doSelect($c);

    	

    	foreach($tbl_distributor as $dist){

    		$c = new Criteria();

    		$c->add(TblAccountLedgerPeer::F_DIST_ID, $dist->getFId());

    		$c->addAnd(TblAccountLedgerPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

	        $c->addAscendingOrderByColumn(TblAccountLedgerPeer::F_CREATED_DATETIME);

	        $tbl_ledger = TblAccountLedgerPeer::doSelect($c);

	        

	        $balance = 0;

	        foreach($tbl_ledger as $ledger){

	        	$balance += $ledger->getFCredit() - $ledger->getFDebit();

	        	$ledger->setFBalance($balance);

	        	$ledger->save();

	        }

	        

	        $c = new Criteria();

	        $c->add(TblAccountPeer::F_DIST_ID, $dist->getFId());

    		$c->addAnd(TblAccountPeer::F_TYPE, Globals::ACCOUNT_TYPE_ECASH);

    		$tbl_account = TblAccountPeer::doSelectOne($c);

    		if($tbl_account){

    			$tbl_account->setFBalance($balance);

    			$tbl_account->save();

    		}

    	}

    	exit;

	}

	

	public function executeRecalculateTradingLimit($id){

		$c = new Criteria();

    	$c->add(TblAccountPeer::F_TYPE, 'cps');

    	$c->addAnd(TblAccountPeer::F_BALANCE, 0, Criteria::GREATER_THAN);

    	$tbl_account = TblAccountPeer::doSelect($c);

    	

    	foreach($tbl_account as $account){

    		$this->adjustTradingLimit($account->getFDistId());

    	}

    	

    	print_r('finish');exit;

	}

	

	function adjustTradingLimit($id){

    	$c = new Criteria();

    	$c->add(TblAccountLedgerPeer::F_DIST_ID, $id);

    	$c->addAnd(TblAccountLedgerPeer::F_TYPE, 'trading point');

    	$c->addAnd(TblAccountLedgerPeer::F_ACTION, array('register','reinvest', 'adjustment'), Criteria::IN);

    	$tbl_ledger = TblAccountLedgerPeer::doSelect($c);

    	

    	$trading_point = 0;

    	foreach($tbl_ledger as $ledger){

    		$trading_point = $trading_point+$ledger->getFCredit()-$ledger->getFDebit();	

    	}

    	

    	$c = new Criteria();

    	$c->add(TblAccountPeer::F_DIST_ID, $id);

    	$c->addAnd(TblAccountPeer::F_TYPE, 'cps');

    	$tbl_account = TblAccountPeer::doSelectOne($c);

    	

    	$cps=0;

    	if($tbl_account){

    		$cps = $tbl_account->getFBalance();

    	}

    	

    	$point = $trading_point/$cps;

    	if($point>1) $point = 0.9;

    	

    	if($cps>=25000){

    		$new_trading_point = $cps * 2 * $point;

    	}elseif($cps>=10000){

    		$new_trading_point = $cps * 1.5 * $point;

    	}else{

    		$new_trading_point = $cps * 1 * $point;

    	}

    	

    	$adjust_point = $new_trading_point - $trading_point;

    	    	

    	$c = new Criteria();

    	$c->add(TblAccountPeer::F_DIST_ID, $id);

    	$c->addAnd(TblAccountPeer::F_TYPE, 'trading point');

    	$tbl_account = TblAccountPeer::doSelectOne($c);

    	

    	$current_trading_point=0;

    	if($tbl_account){

    		$current_trading_point = $tbl_account->getFBalance();

    	}

    	    	

    	$tbl_account_ledger = new TblAccountLedger();

		$tbl_account_ledger->setFDistId($id);

		$tbl_account_ledger->setFType(Globals::ACCOUNT_TYPE_TRADING_POINT);

		$tbl_account_ledger->setFAction(Globals::ACCOUNT_LEDGER_ACTION_ADJUSTMENT);

		if($adjust_point>0){

    		$tbl_account_ledger->setFCredit(abs($adjust_point));

    	}else{

    		$tbl_account_ledger->setFDebit(abs($adjust_point));

    	}		

		$tbl_account_ledger->setFBalance($current_trading_point+$adjust_point);

		$tbl_account_ledger->setFCreatedDatetime(date('Y-m-d H:i:s'));

		$tbl_account_ledger->save();

    	

    	if($tbl_account){

    		$tbl_account->setFBalance($tbl_account_ledger->getFBalance());

    		$tbl_account->save();

    	}

	}



    public function executeWithdrawalStatus(){

        $this->title = "Finance";

    	$this->title2 = "Withdrawal Status";

    }

    /************************************************************************************************************************

     * function

     ************************************************************************************************************************/

    function generateFcode($country = 'China (PRC)') {
		
		if($country == 'Malaysia'){
			$max_digit = 999999;
			$digit = 6;
		}elseif($country == 'Indonesia'){
			$max_digit = 9999999;
			$digit = 7;
		}elseif($country == 'China (PRC)' || $country == 'China'){
			$max_digit = 99999999;
			$digit = 8;
		}else{
			$max_digit = 999999999;
			$digit = 9;
		}

        while (true) {

            $fcode = rand(0, $max_digit)."";

			$fcode = str_pad($fcode, $digit, "0", STR_PAD_LEFT);
			/*
            for ($x=0; $x < ($digit - strlen($fcode)); $x++) {

                $fcode = "0".$fcode;

            }
			*/
            $c = new Criteria();

            $c->add(TblUserPeer::F_USERNAME, $fcode);

            $existUser = TblUserPeer::doSelectOne($c);



            if (!$existUser) {

                break;

            }

        }

        return $fcode;

    }

    

    function generateFPin() {

        while (true) {

            $fpin = rand(0, 999999999999)."";

            for ($x=0; $x < (12 - strlen($fpin)); $x++) {

                $fpin = "1".$fpin;

            }

            

            $c = new Criteria();

            $c->add(TblPinPeer::F_PIN, $fpin);

            $existPin = TblPinPeer::doSelectOne($c);



            if (!$existPin) {

                break;

            }

        }



        return $fpin;

    }



    function getParentId($sponsorId) {

        $userId = 0;



        $c = new Criteria();

        $c->add(TblDistributorPeer::F_CODE, $sponsorId);

        $c->add(TblDistributorPeer::F_STATUS, Globals::STATUS_ACTIVE);

        $existUser = TblDistributorPeer::doSelectOne($c);



        if ($existUser) {

            $userId = $existUser->getFId();

        }



        return $userId;

    }



    function getTradingPower() {

        $tradingPower = 0;



        $c = new Criteria();

        $c->add(TblSettingPeer::F_PARAMETER, Globals::SETTING_TRADING_POWER);

        $exist = TblSettingPeer::doSelectOne($c);



        if ($exist) {

            $tradingPower = $exist->getFValue();

        }



        return $tradingPower;

    }



    function revalidateAccount($distributorId, $accountType) {

        $balance = $this->getAccountBalance($distributorId, $accountType);



        $c = new Criteria();

        $c->add(TblAccountPeer::F_TYPE, $accountType);

        $c->add(TblAccountPeer::F_DIST_ID, $distributorId);

        $tbl_account = TblAccountPeer::doSelectOne($c);



        if (!$tbl_account) {

            $tbl_account = new TblAccount();

            $tbl_account->setFDistId($distributorId);

            $tbl_account->setFType($accountType);

        }

        $tbl_account->setFBalance($balance);

        $tbl_account->save();

    }



    function getAccountBalance($distributorId, $accountType) {

        $query = "SELECT SUM(f_credit-f_debit) AS SUB_TOTAL FROM tbl_account_ledger WHERE f_dist_id = " . $distributorId." AND f_type = '".$accountType."'";



        $connection = Propel::getConnection();

        $statement = $connection->prepareStatement($query);

        $resultset = $statement->executeQuery();



        $count = 0;

        if ($resultset->next()) {

            $arr = $resultset->getRow();

            if ($arr["SUB_TOTAL"] != null) {

                return $arr["SUB_TOTAL"];

            } else {

                return 0;

            }

        }

        

        return 0;

    }



    function verifyGapDay($distributorId, $checkDate) {

        $c = new Criteria();

        $c->add(TblAccountLedgerPeer::F_DIST_ID, $distributorId);

        $c->addAnd(TblAccountLedgerPeer::F_TYPE, Globals::ACCOUNT_TYPE_GAP);

        $c->addAnd(TblAccountLedgerPeer::F_BALANCE, 0);

        $c->addDescendingOrderByColumn(TblAccountLedgerPeer::F_ID);



        $exist = TblAccountLedgerPeer::doSelectOne($c);

        // check gap and balance = 0

        if ($exist) {

            $gapCreatedDatetime = $exist->getFCreatedDatetime();



            $frmtdate = $gapCreatedDatetime;



            $dateDiff = strtotime($checkDate)-strtotime($frmtdate);

            $noOfDays = floor($dateDiff/(60*60*24));



            if ($noOfDays <= Globals::REINVEST_CPS_DAYS) {

                return true;

            } else {

                return false;

            }

        }



        return false;

    }

    

    function retrieve_gen_downline($in_upline_id, $which_network, $aj_query_name, $retrieve_level = 1){

		

		$cur_level = 0;

		$uplines[$cur_level][0] = $in_upline_id;

		do{

			$nli = 0;

			$next_level = $cur_level + 1;

			for($i=0,$t=count($uplines[$cur_level]);$i<$t;$i++){

				$upline_id = $uplines[$cur_level][$i];

				

				$query = "SELECT * FROM tbl_distributor WHERE $which_network=".$upline_id;

				$connection = Propel::getConnection();

		        $statement = $connection->prepareStatement($query);

		        $r2 = $statement->executeQuery();

				

				for($j=0;$j<count($r2);$j++){

					if ($r2->next()) {

            			$downline = $r2->getRow();

					

						$c = new Criteria();

						$c->add(TblDistributorPeer::F_PARENTID, $downline['f_id']);

						$c->addAnd(TblDistributorPeer::F_STATUS, Globals::STATUS_ACTIVE);

						$isparent = TblDistributorPeer::doSelect($c);

						if($isparent){

							//$have_downline = true;

							$have_downline = false;

							$display_pic = "m";

						}else{

							$have_downline = false;

							$display_pic = "m";

						}



						$base_info_width = 290;

						$char_width = 9;

						$display_pic = "/js/jqtree/images/node{$display_pic}.gif";

						$strlen = strlen($downline['f_nickname']);

						$downline_width=$base_info_width + ($strlen * ($char_width) + 10);

						$display_value="<span class='gen_img'><img src='$display_pic' /></span> <span class='gen_id'>".$downline["f_code"]."</span> <span class='gen_name'>".$downline["f_nickname"]."</span> ".

						"<span class='gen_jdate'>Joined ".date('Y-m-d', strtotime($downline["f_active_datetime"]))."</span>";

						$downlines[$upline_id][$j]['id'] = $downline['f_id'];

						$downlines[$upline_id][$j]['width'] = $downline_width + 100;

						$downlines[$upline_id][$j]['username'] = $downline['f_nickname'];

						$downlines[$upline_id][$j]['node'] = "<div class='tree-node'>$display_value</div><div class='clear'></div>";

						$downlines[$upline_id][$j]['have_downline'] = ($next_level >= $retrieve_level && $have_downline)? true : false;

						$uplines[$next_level][$nli++] = $downline['f_id'];

					}

				}

			}

			$cur_level++;

		}while($cur_level < $retrieve_level && count($uplines[$cur_level]));

		unset ($uplines);

		if($downlines){

			$upline_id = $in_upline_id;

			$uplines[0] = $upline_id;

			do{

				$ui = 0;

				unset($next_uplines);

				for($i=0,$t=count($uplines);$i<$t;$i++){

					$upline_id = $uplines[$i];

					unset($replace_later);

					for($j=0,$t2=count($downlines[$upline_id]);$j<$t2;$j++){

						$downline = $downlines[$upline_id][$j];

						$this_node = "

						<li id='$downline[id]' style='width:550px;'>$downline[node]".($downline['have_downline']? "<ul class='ajax'><li>{url:member/sponsorTree?$aj_query_name=1&id=$downline[id]&aj=1}</li></ul>" : "")."{{$downline[id]}}</li>";

						if(strstr($downline_node, "{{$upline_id}}")){

							$replace_later .= $this_node;

						}else{

							$downline_node .= $this_node;

						}

						$next_uplines[$ui++] = $downline['id'];

					}

					if($replace_later){

						$downline_node = str_replace("{{$upline_id}}", "\n<ul>$replace_later</ul>{{$upline_id}}", $downline_node);

					}

				}

				$uplines = $next_uplines;

			}while($next_uplines);

			$downline_node = preg_replace('/\{[0-9]+\}/', '', $downline_node);

		}

		

		return $downline_node;

	}

	

	function rebuild($parent,$left,$level) {

		$right=$left+1;

		if(isset($this->atree1[$parent])) {

			foreach($this->atree1[$parent] as $key=>$child)

				$right=$this->rebuild($child['f_id'],$right,$level+1);

		}

		if($this->atree[$parent]['f_right']!=$right){

			$dist = TblDistributorPeer::retrieveByPk($parent);

			$dist->setFLeft2($left);

			$dist->setFRight2($left);

			$dist->setFLevel2($left);

			$dist->save();

		}

		

		unset($this->atree[$parent]['f_right']);

		return $right+1;

	}

	

	

	function rebuildplacement($rootid=1)

	{

		$c = new Criteria();

		$c->add(TblDistributorPeer::F_PARENTID2, 0, Criteria::GREATER_EQUAL);

		//$c->addAnd(TblDistributorPeer::F_STATUS, Globals::STATUS_ACTIVE);

		$TblDist = TblDistributorPeer::doSelect($c);

		

		$arrTree = array();

		foreach($TblDist as $dist)

		{

			$nParentID = $dist->getFParentid2();

			$dataTemp  = array();

			$dataTemp['id']    = $dist->getFId();

			$arrTree[$nParentID][] = $dataTemp;

		}



		$rootID = 0;

		if((isset($arrTree[0])) && (sizeof($arrTree[0])>0))

		{

			$rootID = $arrTree[0][0]['id'];

		}



		if($rootID<=0)

		{

			return false;

		}



		$this->rebuild_tree($rootID,1,1,1, $arrTree);

		return true;



	}



	function rebuild_tree($nParentID,$left,$nlevel,$seq, $arrTree)

	{

		$right = $left+1;



		$subNodeInfo   = @(isset($arrTree[$nParentID]))?$arrTree[$nParentID]:array();



		$subSize       = sizeof($subNodeInfo);

		if($subSize>0)

		$isparent = 1;

		else

		$isparent=0;



		if($subSize>0)

		{

			$seqno = 0;

			foreach($subNodeInfo as $key=>$nodeInfo)

			{

				$right = $this->rebuild_tree($nodeInfo['id'],$right,$nlevel+1,$seqno+1, $arrTree);

				$seqno++;

			}

		}



		$dist = TblDistributorPeer::retrieveByPk($nParentID);

		$dist->setFLeft2($left);

		$dist->setFRight2($right);

		$dist->setFLevel2($nlevel);

		$dist->save();



		return $right+1;

	}

	

	function format2decimal($d){

        return ceil($d * 100) / 100;

    }



    function checkHasChild($distId) {

        $c = new Criteria();

        $c->add(TblDistributorPeer::F_PARENTID, $distId);

        $c->addAnd(TblDistributorPeer::F_STATUS, Globals::STATUS_ACTIVE);

        $list = TblDistributorPeer::doSelect($c);

        if($list){

            return true;

        }



        return false;

    }



}